接口中的构造函数?

2022-08-31 07:21:11

我知道不可能在接口中定义构造函数。但我想知道为什么,因为我认为它可能非常有用。

因此,您可以确保为该接口的每个实现定义了类中的某些字段。

例如,请考虑以下邮件类:

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
   }
}

如果为这个类定义一个接口,以便我可以有更多的类来实现消息接口,我只能定义发送方法,而不能定义构造函数。那么,如何确保此类的每个实现都确实具有接收器集?如果我使用这样的方法,我无法确定此方法是否真的被调用。在构造函数中,我可以确保它。setReceiver(String receiver)


答案 1

以你所描述的一些事情为例:

“因此,您可以确保为该接口的每个实现定义了类中的某些字段。

“如果为这个类定义一个接口,以便我可以有更多的类来实现消息接口,我只能定义发送方法,而不能定义构造函数”

...这些要求正是抽象类的用途。


答案 2

当您允许在接口中使用构造函数时,您遇到的一个问题来自同时实现多个接口的可能性。当一个类实现定义不同构造函数的多个接口时,该类必须实现多个构造函数,每个构造函数只满足一个接口,而不满足其他接口。构造一个调用这些构造函数中的每一个的对象是不可能的。

或在代码中:

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); 
  }
}