Constructor in a Interface?
Posted
by Sebi
on Stack Overflow
See other posts from Stack Overflow
or by Sebi
Published on 2010-05-10T15:41:12Z
Indexed on
2010/05/10
15:44 UTC
Read the original article
Hit count: 349
I know its not possible to define a constructor in a interface. But im wondering why, because i think i could be very useful.
So you could be sure that some fields in a class are defined for every implementaiton 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 a 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 assure that every implementation of this class really has an receiver setted? 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 assure it.
© Stack Overflow or respective owner