How is inheritance implemented in Java?

吃可爱长大的小学妹 提交于 2019-12-10 11:59:20

问题


How exactly is inheritance implemented in Java? For example, consider this:

class A {
    public void foo() {
         System.out.print("A");
    }
}
class B extends A {
    ...
}
class Test {
    public static void main(String[] args) {
        B test = new B();
        test.foo(); // how is foo() called?
}

Below the line, would the compiler just dump the definition of A.foo() into the body of class B? Like

class B extends A {
    ...
    public void foo() {
         System.out.print("A");
    }
}

Or is foo somehow looked up in class A and called there?


回答1:


Method bodies aren't copied in the undefined method body of a subclass. Instead, when you call

B test = new B();
test.foo();

It will look trough its hierarchy, going up a level every time it can't find an implementation. First it will check B which has no implementation. One level above that there's A which does, so it will use that one.




回答2:


This may be able to assist you, explanation from the book Ivor Horton's Begining Java 7

I said at the beginning of this chapter that a derived class extends a base class. This is not just jargon — it really does do this. As I have said several times, inheritance is about what members of the base class are accessible in a derived class, not what members of the base class exist in a derived class object. An object of a subclass contains all the members of the original base class, plus any new members that you have defi ned in the derived class. This is illustrated in Figure 6-3.



来源:https://stackoverflow.com/questions/19241499/how-is-inheritance-implemented-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!