当您调用构造函数(新类)时,实例初始化程序块首先运行会发生什么事情? [英] What exaclty happens when a you call a constructor(new Class),do instance initializer blocks runs first?
问题描述
我是Java尤其是OOP的一个完整的初学者,所以请原谅我的天真,但是最近在经历Head First Java时,他们说,构造函数是当有人说 new 时运行的代码
但是我尝试了这段代码以查看实际发生了什么,但是令我惊讶的是输出完全不同。
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);}
}
输出:
Hello World!
Out1 0
Out2 0
内部构造函数
我的问题:为什么?我调用构造函数初始化特定的实例变量后,实例变量是否应立即初始化?这是否意味着构造函数的全部目的要在制造对象之前运行!
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:
- 调用超类的构造函数。
- 运行
- 执行构造函数的其余部分。
即,两个sysout语句都在赋值 n = 10;
之前执行。那就是应该的。请参见 JLS§12.5。
I.e., both of your sysout statements execute just before the assignment n=10;
. That's how it should be. See JLS §12.5.
这篇关于当您调用构造函数(新类)时,实例初始化程序块首先运行会发生什么事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!