简体   繁体   中英

Java inheritance method call

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?

Super.hello()调用this.say(),后者引用当前对象(即派生对象),因此调用派生类的say方法。

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

So due to overriding Derived class method is called.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM