0

I have a interesting scenario that.

public class Base {

    public void hello(){
        this.say();
        System.out.println("hello-Base");
    }

    protected void say(){
        System.out.println("say-Base");
    }
}



public class Derived extends Base {

    public Derived(){
        super.hello();      
    }

    public static void main(String[] args) {
        Derived d = new Derived();      
    }

    public void say(){
        System.out.println("say-Derived");
    }

}

The output given is that:

say-Derived
hello-Base

I was expecting that when super.hello() method was invoked, say() method of Base classes was invoked rather than say()method of Derived class.

What is the reason behind this logic?

1
  • 6
    this is a Derived Commented Dec 4, 2012 at 9:46

3 Answers 3

2

Super.hello() calls this.say() which(this) refer to the current object i.e. derived so it calls the say method of derived class.

Sign up to request clarification or add additional context in comments.

Comments

1

Because this -- points to ---> Instance of Type Derived

So due to overriding Derived class method is called.

Comments

1

super.hello(); is raised from Derived constructor i.e. object of derived class. Which in turns calls this.say() i.e. derived.say(). So that's why the output is so.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.