Java-在默认构造函数之前执行的方法 [英] Java - Method executed prior to Default Constructor
本文介绍了Java-在默认构造函数之前执行的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Java,偶然发现了以下代码,该方法之后将执行默认构造函数。
I'm learning java and accidentally I came across following code where default constructor is executed after the method.
public class ChkCons {
int var = getVal();
ChkCons() {
System.out.println("I'm Default Constructor.");
}
public int getVal() {
System.out.println("I'm in Method.");
return 10;
}
public static void main(String[] args) {
ChkCons c = new ChkCons();
}
}
输出:
I'm in Method.
I'm Default Constructor.
有人可以解释一下为什么会这样吗?
Can anyone please explain me why this happened?
谢谢。 p>
Thanks.
推荐答案
实例变量初始化表达式,例如 int var = getVal();
是在超类构造函数执行之后但在当前类构造函数的主体执行之前进行求值。
Instance variable initialization expressions such as int var = getVal();
are evaluated after the super class constructor is executed but prior to the execution of the current class constructor's body.
因此, getVal()$ c $在执行
ChkCons
构造函数的主体之前调用c>。
Therefore getVal()
is called before the body of the ChkCons
constructor is executed.
这篇关于Java-在默认构造函数之前执行的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文