I read in a book that instance members are accessible only after the super constructor runs.
I stumbled upon the following code:
class Parent {
Parent() {
printIt();
}
void printIt() {
System.out.println("I'm in a overridden method. Great.");
}
}
class Child extends Parent {
int i = 100;
public static void main(String[] args) {
Parent p = new Child();
p.printIt();
}
void printIt() {
System.out.print(i + " ");
}
}
and it prints:
0 100
My question would be:
If instance members are accessible only after the super constructor runs, then why is it that upon execution of the printIt( ) method of class Parent, (which in fact is Child's printIt( ) due to polymorphism), it was able to access the uninitialized instance variable i of Child even though the constructor of Parent has not yet finished executing?
What am I missing?
I read in a book that instance members are accessible only after the super constructor runs.
Your book is wrong (if that's what it really says). They are accessible at all times once construction has started. However they are not initialized until after the super constructor has run. So what you printed was the default value: null, zero, or false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With