开发者

Can some explain what this code means in Java?

开发者 https://www.devze.com 2023-02-25 03:20 出处:网络
There\'s a program I\'m looking at and it contains a line that I don\'t understand. NoticeBoard notice = (NoticeBoard) o;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号