接口中的构造函数? [英] Constructor in an Interface?
问题描述
我知道在界面中定义构造函数是不可能的。但我想知道为什么,因为我认为它可能非常有用。
I know it's not possible to define a constructor in an interface. But I'm wondering why, because I think it could be very useful.
所以你可以确定类中的某些字段是为这个接口的每个实现定义的。
So you could be sure that some fields in a class are defined for every implementation of this interface.
例如,考虑以下消息类:
For example consider the following message class:
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)
这样的方法,我无法确定是否真的调用了这个方法。在构造函数中,我可以确保它。
If a define an interface for this class so that I can have more classes which implement the message interface, I can only define the send method and not the constructor. So how can I ensure that every implementation of this class really has an receiver set? If I use a method like setReceiver(String receiver)
I can't be sure that this method is really called. In the constructor I could ensure it.
推荐答案
采取你所描述的一些事情:
Taking some of the things you have described:
所以你可以确定一个类中的某些字段是为每个实现这个接口的
定义的。
"So you could be sure that some fields in a class are defined for every implementation of this interface."
如果为这个类定义一个接口,这样我可以有更多的
类来实现消息接口,我只能定义
send方法而不是构造函数
"If a define a Interface for this class so that I can have more classes which implement the message interface, I can only define the send method and not the constructor"
......这些要求正是抽象类适用于。
...these requirements are exactly what abstract classes are for.
这篇关于接口中的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!