Mr Teeth
Mr Teeth

Reputation: 1299

Can some explain what this code means in Java?

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" );
    }
}

Upvotes: 0

Views: 161

Answers (2)

Krumelur
Krumelur

Reputation: 33048

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.

Upvotes: 1

Daff
Daff

Reputation: 44205

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.

Upvotes: 3

Related Questions