I have tried to do some research on how Subclasses are able to access the methods and fields of the Superclasses. When I read a post on stackoverflow that explained how inheritance 'really' works, I was confused to see my output. The post I read was: What really happens on inheritance in Java?
After having read this post, this is my understanding on inheritance which I ask you to correct if wrong:
- Methods and fields are not copied to the subclass, but are instead called from a Superclass object unless overridden in a Subclass. I have confirmed methods and fields not being copied to the subclass by using the javap command.
- When calling a method in a Subclass, it looks during runtime for the method in the Subclass object (a possible overriding method) and if it is not found it will go up in hierarchy to find it in a Superclass object and then call it from a Superclass object.
- Because methods and fields are not copied to the Subclass but are instead called from a Superclass object, the Subclass constructor calls super(); implicitly to make sure there's a Superclass object available to call inherited methods from.
Applying the logic I just wrote down, I came across some weird outputs. In the example below I have class A (Superclass) and class B (Subclass). I received B as output from the Main method but was instead expecting A as output.
Class A:
public class A {
public void getTheClass() {
System.out.println(getClass().getSimpleName());
}
}
Class B:
public class B extends A {
public B() {
getTheClass();
}
}
Class Main:
public class Main {
public static void main(String[] args) {
B b = new B();
}
}
The reason why I expected A as output, is because (according to the earlier described logic) the getTheClass() method will be called from the Superclass object (A) as the Subclass object (B) does not have a method named getTheClass(). The Subclass object does not have this method because according to my understanding, methods and fields are not copied to Subclasses.
If the Subclass does not have this method, it will go up in hierarchy to search for an object that does and call it from there, which in this case would be the Superclass object (A). So if the getTheClass() method is called from the Superclass object (A), wouldn't the class of the object be class A rather than class B? And in that case, why did it not output A but instead B? I get the same confusing result if I print out the keyword this.