There's a program I'm looking at and it contains a line that I don't understand.
NoticeBoard notice = (NoticeBoard) o;
What is that piece of code doing?
That line is taken from here (posting this because you guys might want to understand the full context of the line):
import java.util.Observable;
import java.util.Observer;
class NoticeBoard extends Observable
{
private String theNotice = "";
public void setTheNotice( final String notice )
{
开发者_运维问答 theNotice = notice;
setChanged();
notifyObservers();
}
public String getTheNotice()
{
return theNotice;
}
}
class NoticeBoardObserver implements Observer
{
public void update( Observable o, Object arg )
{
NoticeBoard notice = (NoticeBoard) o;
System.out.println( notice.getTheNotice() );
}
}
class Main
{
public static void main( String args[] )
{
NoticeBoard floor4 = new NoticeBoard();
NoticeBoardObserver anObserver = new NoticeBoardObserver();
floor4.addObserver( anObserver );
floor4.setTheNotice( "Its summer" );
}
}
It is casting the Observable Object named o to an instance of NoticeBoard. Better would be to check before if o is an instance of NoticeBoard (or else you get a ClassCastException if it isn't):
if(o instanceof NoticeBoard) {
NoticeBoard notice = (NoticeBoard) o;
System.out.println( notice.getTheNotice() );
}
Typecasts should be avoided if possible (e.g. by using Java Generics) but here it is needed to comply with the Observer interface signature.
The line you refer to is a cast. Observable o
gets cast to NoticeBoard
.
It seems like the code you posted implements an Observer-Observable pattern (http://en.wikipedia.org/wiki/Observer_pattern). The oject gets notified about a change (public void update()
) and passes a generic Observable which in your case is a NoticeBoard
object.
To be able to access the NoticeBoard
object's specific methods, it has to be cast.
精彩评论