This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyClass { | |
MyClass() { | |
System.out.println("MyClass"); | |
} | |
MyClass(String id) { | |
System.out.println("MyClass " + id); | |
} | |
} | |
class Parent { | |
// static String id = "Parent"; | |
// MyClass instance1 = new MyClass(id); | |
MyClass instance1 = new MyClass(); | |
Parent() { | |
System.out.println("Parent"); | |
} | |
} | |
public class Test extends Parent { | |
// static String id = "Test"; | |
// MyClass instance2 = new MyClass(id); | |
MyClass instance2 = new MyClass(); | |
Test(String name) { | |
System.out.println("Test"); | |
} | |
public static void main(String[] args) { | |
new Test("Cristina"); | |
} | |
} | |
The answer is:
MyClass
Parent
MyClass
Test
Now can you tell which instance (instance1 or instance2) prints the first "MyClass" string?
Uncomment the commented lines and see for yourself!
http://stackoverflow.com/questions/14805547/are-fields-initialized-before-constructor-code-is-run-in-java
http://stackoverflow.com/questions/17806342/order-of-constructor-calls-in-multilevel-inheritance-in-java