Constructor in an Interface?

前端 未结 11 1043
鱼传尺愫
鱼传尺愫 2020-12-02 06:38

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 fi

11条回答
  •  情深已故
    2020-12-02 07:12

    If you want to make sure that every implementation of the interface contains specific field, you simply need to add to your interface the getter for that field:

    interface IMyMessage(){
        @NonNull String getReceiver();
    }
    
    • it won't break encapsulation
    • it will let know to everyone who use your interface that the Receiver object has to be passed to the class in some way (either by constructor or by setter)

提交回复
热议问题