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!
The constructor executes in the following order:
I.e., both of your sysout statements execute just before the assignment
n=10;
. That's how it should be. See JLS §12.5.