Tuesday 2 January 2018

java - Constructor in an Interface?

itemprop="text">

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.



Answer




Taking some of the things you have
described:






"So you could be sure that some fields in a class are defined for

every implementation of this interface."



"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"




...these
requirements are exactly what href="http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html"
rel="noreferrer">abstract classes are for.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...