Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top