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
}
}
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.
No comments:
Post a Comment