问题
Im a complete beginner in the Java especially OOP so please pardon my naivety but recently while going through Head First Java,they said,A constructor is a code that runs when somebody says new on a class type. But then i tried this code to see what actually happened but to my surprise the output was totally different.
public class Test {
private int n;
{System.out.println("Out1 "+n);}
public Test() {
n=10;
System.out.println("Inside Constructor");
}
public static void main(String args[]) {
System.out.println("Hello World!");
Test obj=new Test();
}
{System.out.println("Out2 "+n);}
}
The Output:
Hello World!
Out1 0
Out2 0
Inside Constructor
My question:WHY?Shouldnt the instance variable get initialized as soon as i call the contructor to initialize the specific instance variable?Isnt that the whole purpose of constructors?to run before making the object!
回答1:
The constructor executes in the following order:
- Calls the constructor of the superclass.
- Runs the instance initializer blocks in the order they were defined.
- Executes the rest of the body of the constructor.
I.e., both of your sysout statements execute just before the assignment n=10;. That's how it should be. See JLS §12.5.
来源:https://stackoverflow.com/questions/24109439/what-exaclty-happens-when-a-you-call-a-constructornew-class-do-instance-initia