I know about static and intialization block in a class and their order of execution. But the following code causes some doubts.
class Test1 {
Test1(int x) {
System.out.println("Constructor value : " + x);
}
}
public class Test2 {
Test1 t1 = new Test1(10); ----- line 8
Test2(int i) {
t1 = new Test1(i);
}
public static void main(String[] args) {
Test2 t2 = new Test2(5);
}
}
This code's output :
Constructor value : 10
Constructor value : 5
My question is that the instance variable (line 8) is executed as soon as the object for the class(Test2) is created or some other stuff happens.
Initializers and initialization blocks are executed as though they were inserted into every constructor right at the top (in a base class) or just after the call to super(...)
(in a subclass).¹ So your Test2
is functionally identical to:
public class Test2 {
Test1 t1;
Test2(int i) {
t1 = new Test1(10);
t1 = new Test1(i);
}
public static void main(String[] args) {
Test2 t2 = new Test2(5);
}
}
¹ In fact, that's literally true if you look at the bytecode...
For instance, suppose we add a second constructor to Test2
:
public class Test2 {
Test1 t1 = new Test1(10);
Test2(int i) {
t1 = new Test1(i);
}
Test2(int i, String s) {
t1 = new Test1(i);
}
public static void main(String[] args) {
Test2 t2 = new Test2(5);
}
}
then compile it, and use javap -c Test2
to see the bytecode (roughly):
Compiled from "Test2.java" public class Test2 { Test1 t1; Test2(int); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: aload_0 5: new #2 // class Test1 8: dup 9: bipush 10 11: invokespecial #3 // Method Test1."<init>":(I)V 14: putfield #4 // Field t1:LTest1; 17: aload_0 18: new #2 // class Test1 21: dup 22: iload_1 23: invokespecial #3 // Method Test1."<init>":(I)V 26: putfield #4 // Field t1:LTest1; 29: return Test2(int, java.lang.String); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: aload_0 5: new #2 // class Test1 8: dup 9: bipush 10 11: invokespecial #3 // Method Test1."<init>":(I)V 14: putfield #4 // Field t1:LTest1; 17: aload_0 18: new #2 // class Test1 21: dup 22: iload_1 23: invokespecial #3 // Method Test1."<init>":(I)V 26: putfield #4 // Field t1:LTest1; 29: return public static void main(java.lang.String[]); Code: 0: new #5 // class Test2 3: dup 4: iconst_5 5: invokespecial #6 // Method "<init>":(I)V 8: astore_1 9: return }
You can see the t1 = new Test1(10)
in both constructors.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments