为什么在显式调用构造函数时不能引用实例方法?
2022-09-01 03:19:42
有谁知道为什么你可以使用 or 在构造函数的第一行引用一个方法,而不是一个非静态方法?static
this()
super()
请考虑以下工作:
public class TestWorking{
private A a = null;
public TestWorking(A aParam){
this.a = aParam;
}
public TestWorking(B bParam)
{
this(TestWorking.getAFromB(bParam));
}
//It works because its marked static.
private static A getAFromB(B param){
A a = new A();
a.setName(param.getName());
return a;
}
}
以及以下非工作示例:
public class TestNotWorking{
private A a = null;
public TestNotWorking(A aParam){
this.a = aParam;
}
public TestNotWorking(B bParam)
{
this(this.getAFromB(bParam));
}
//This does not work. WHY???
private A getAFromB(B param){
A a = new A();
a.setName(param.getName());
return a;
}
}