【发布时间】:2014-07-21 19:55:16
【问题描述】:
有效代码1:
class ClassForTest{
ClassForTest(int k){
};
ClassForTest(){
this(2);
method();
};
int method(){return 1;}
}
我的解决方案 - 我可以在构造函数中调用非静态方法!
无效代码
class ClassForTest{
ClassForTest(int k){
};
ClassForTest(){
this(method());
};
int method(){return 1;}
}
编译错误:
java: cannot reference this before supertype constructor has been called
有效代码2:
class ClassForTest{
ClassForTest(int k){
};
ClassForTest(){
this(method());
};
static int method(){return 1;}
}
有效代码3:
class ClassForTest{
ClassForTest(int k){
};
{
method();
}
ClassForTest(){
this(1);
};
int method(){return 1;}
}
这个行为集对我来说很奇怪。
你能解释一下吗?
更新
据我了解,编译器会合并以下初始化块:
constructor(){
super();
nonStaticInitBlock;
remain constructor code;
}
我不明白为什么我不能将此调用用作构造函数的参数
编辑
在最后一次构造函数调用之后调用实例初始化器。 – Sotirios Delimanolis 6 月 1 日 17:17
@Sotirios 你错了
研究这段代码:
public class Order {
{
System.out.println("initializer!");
}
Order(){
System.out.println("constructor");
}
public static void main(String [] args){
new Order();
}
}
结果:
initializer!
constructor
【问题讨论】:
-
in重复的问题没有解释有效代码3
-
实例初始化器在最后一次构造函数调用之后被调用。
-
public class Order { {public class Order { { System.out.println("initializer!"); } Order(){ System.out.println("constructor"); } public static void main(String [] args){ new Order(); } } System.out.println("初始化器!"); } Order(){ System.out.println("constructor"); } public static void main(String [] args){ new Order(); } }
-
@Sotirios Delimanolis 你错了
-
我可以在初始化块中引用这个指针。此块在构造函数之前执行,因此未设计对象但我可以调用它。
标签: java methods constructor instance