I think we already discussed this issue in this article here Inheritance in a simple Java explanation
But since the example here is a little simpler, and the point I want to clarify is different, I will take a picture.
First, consider two classes:
public class SuperClass{
SuperClass() {
foo();
}
public void foo() {
System.out.println("Super.foo()");
}
public static void main(String[] args) {
SuperClass tn = new DerivedClass();
tn.foo();
}
}
public class DerivedClass extends SuperClass{
String i;
TrickyB() {
i = "aksjhdf";
}
public void foo() {
System.out.println("In derived.foo() --> " + i);
}
}
I (at least I think) understand the concepts of polymorphism, and I know why it DerivedClass.foo()is called when called
new DerivedClass();
I see inconsistency here:
At the time we call c'tor of DerivedClass, c'tor SuperClassis called implicit (so to speak, like the first line of the c'tor derivative).
So, Super c'tor is DerivedClassnot fully initialized, which makes working with this class useless. This point is reflected in the output of this program.
In derived.foo() --> null
In derived.foo() --> aksjhdf
:
DerivedClass.foo()? , - .
- . , .
BTW: , SuperClass.foo() , , , "" .
: . , , c'tor SuperClass, DerivedClass.foo()!
SuperClass.foo() ?