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.
Taking some of the things you have described:
…these requirements are exactly what abstract classes are for.