What exaclty happens when a you call a constructor(new Class),do instance initializer blocks runs first? [closed]

跟風遠走 提交于 2019-12-14 00:09:04

问题


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:

  1. Calls the constructor of the superclass.
  2. Runs the instance initializer blocks in the order they were defined.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!