问题
我知道在界面中定义构造函数是不可能的。但我想知道为什么,因为我觉得它可能非常有用。
因此,你可以确保为此接口的每个实现定义了类中的某些字段。
例如,考虑以下消息类:
public class MyMessage {
public MyMessage(String receiver) {
this.receiver = receiver;
}
private String receiver;
public void send() {
//some implementation for sending the mssage to the receiver
}
}
如果为这个类定义一个接口,以便我可以有更多的类来实现消息接口,那么我只能定义send方法而不是构造函数。那么我怎样才能确保这个类的每个实现都有一个接收器集?如果我使用像setReceiver(String receiver)
这样的方法,我不能确定这个方法是否真的被调用。在构造函数中,我可以确保它。
#1 热门回答(117 赞)
采取你所描述的一些事情:
"因此,你可以确定为此接口的每个实现定义了类中的某些字段。" "如果为这个类定义一个接口,以便我可以有更多的类来实现消息接口,那么我只能定义send方法而不是构造函数"
......这些要求正是abstract classes所针对的。
#2 热门回答(63 赞)
在接口中允许构造函数时遇到的问题来自于同时实现多个接口的可能性。当一个类实现了几个定义不同构造函数的接口时,该类必须实现几个构造函数,每个构造函数只满足一个接口,而不满足其他接口。构造一个调用每个构造函数的对象是不可能的。
或者在代码中:
interface Named { Named(String name); }
interface HasList { HasList(List list); }
class A implements Named, HasList {
/**implements Named constructor.
* This constructor should not be used from outside,
* because List parameter is missing
*/
public A(String name) {
...
}
/**implements HasList constructor.
* This constructor should not be used from outside,
* because String parameter is missing
*/
public A(List list) {
...
}
/**This is the constructor that we would actually
* need to satisfy both interfaces at the same time
*/
public A(String name, List list) {
this(name);
// the next line is illegal; you can only call one other super constructor
this(list);
}
}
#3 热门回答(10 赞)
接口定义API的合同,API是API的实现者和用户都同意的一组方法。接口没有实例化实现,因此没有构造函数。
你描述的用例类似于一个抽象类,其中构造函数调用在子类中实现的抽象方法的方法。
这里固有的问题是,在执行基础构造函数时,子对象尚未构造,因此处于不可预测的状态。
总结一下:从父构造函数调用重载方法时,它是否会出现问题,引用为mindprod:
通常,你必须避免在构造函数中调用任何非final方法。问题是派生类中的实例初始化器/变量初始化是在基类的构造函数之后执行的。