为什么在显式调用构造函数时不能引用实例方法? [英] Why can't I refer to an instance method while explicitly invoking a constructor?
问题描述
有没有人知道你为什么可以使用 this()在构造函数的第一行中引用
static
或 super()
,但不是非静态方法?
Does anyone know why you can reference a static
method in the first line of the constructor using this()
or super()
, but not a non-static method?
Consider the following working:
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;
}
}
推荐答案
静态方法是实例方法。这只能在现有实例中访问,并且当你在构造函数中时,它还不存在(它仍在构建中)。
Non-static methods are instance methods. This are only accessible in existing instance, and instance does not exist yet when you are in constructor (it is still under construction).
为什么会这样?因为实例方法可以访问实例(非静态)字段,在不同的实例中可以有不同的值,因此将这样的方法调用到除现有的完成实例之外的其他东西是没有意义的。
Why it is so? Because instance methods can access instance (non-static) fields, which can have different values in different instances, so it doesn't make sense to call such method on something else than existing, finished instance.
这篇关于为什么在显式调用构造函数时不能引用实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!