Constructor in an Interface? Ask Question

Constructor in an Interface? Ask Question

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 class:


public class MyMessage {

   private String receiver;

   public MyMessage(String receiver) {
       this.receiver = receiver;
   }

   public void send() {
       // some implementation for sending the message to the receiver
   }
}

If I define a Message 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 its receiver initialized? If I define a method like setReceiver(String receiver), I can't be sure that this method is really called. In the constructor however, I could ensure it.

ベストアンサー1

Taking some of the things you have described:

「したがって、クラス内の一部のフィールドは、このインターフェースのすべての実装に対して定義されていると確信できます。」

「このクラスのインターフェースを定義して、メッセージ インターフェースを実装するクラスをさらに作成できるようにする場合、コンストラクターではなく、送信メソッドのみを定義できます。」

...これらの要件はまさに抽象クラスのためです。

おすすめ記事