请考虑以下类:
class MyClass extends Parent {
private AnotherClass property;
public MyClass(int value) {
super(new AnotherClass(value));
this.property = new AnotherClass(value);
}
}
class AnotherClass {
/* Implementation not shown */
}
class Parent {
/* Implementation not shown, and may not be changed */
}
在不更改构造函数参数的情况下,(例如:MyClass(AnotherClass value)
),我如何构建它以便 new AnotherClass()
不会被调用两次?
以下是无效的示例:
public MyClass(int value) {
AnotherClass anotherClass = new AnotherClass(value);
super(anotherClass);
this.property = anotherClass;
}
它会引发一个错误,指出对 super 的调用必须在第一行。
我正在创建需要双重分派(dispatch)的东西,并且我可能不会更改 MyClass
的实例化方式。 (新的 MyClass(0)
)。我也可能不会碰 super 类。
是否可以只调用一次AnotherClass?
最佳答案
移动它使用两个构造函数
public MyClass(int value) {
this (new AnotherClass(value));
}
public MyClass(AnotherClass a) {
super(a);
this.property = a;
}
注意
这也是@alfasin 建议的
关于java - super 中的Unnest方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24278179/