Unlike C++, the Java programming language does not specify altered rules for method dispatch during the creation of a new class instance. If methods are invoked that are overridden in subclasses in the object being initialized, then these overriding methods are used, even before the new object is completely initialized. Thus, compiling and running the example:
class Super {
Super() { printThree(); }
void printThree() { System.out.println("three"); }
}
class Test extends Super {
int three = (int)Math.PI;
// That is, 3
public static void main(String[] args) {
Test t = new Test();
t.printThree();
}
void printThree() { System.out.println(three); }
}
produces the output:
0
3
This shows that the invocation of printThree in the constructor for class Super does not invoke the definition of printThree in class Super, but rather invokes the overriding definition of printThree in class Test. This method therefore runs before the field initializers of Test have been executed, which is why the first value output is 0, the default value to which the field three of Test is initialized. The later invocation of printThree in method main invokes the same definition of printThree, but by that point the initializer for instance variable three has been executed, and so the value 3 is printed.
Why does Java does not initialize members like in C++... Maybe this question is too complex to be answered
No, that question is very simple. Java isn't C++.Pierre-Yves Langlois wrote:Why does Java does not initialize members like in C++... Maybe this question is too complex to be answered
Don't get me started about those stupid light bulbs. |