top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Whai is Observer and Observable in Java?

0 votes
272 views
Whai is Observer and Observable in Java?
posted Mar 8, 2016 by Niharika Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Observable is a class and Observer is an interface
Observable class maintain a list of observers
and When an Observable object is updated it invokes the update() method of each of its observers to notify that, it is changed
for example
import java.util.Observable;
import java.util.Observer;

class MessageBoard extends Observable {
private String message;

public String getMessage() {
return message;
}

public void changeMessage(String message) {
this.message = message;
setChanged();
notifyObservers(message);
}

public static void main(String[] args) {
MessageBoard board = new MessageBoard();
Student bob = new Student();
Student joe = new Student();
board.addObserver(bob);
board.addObserver(joe);
board.changeMessage("More Homework!");
}
}

class Student implements Observer {
public void update(Observable o, Object arg) {
System.out.println("Message board changed: " + arg);
}
}

answer Mar 9, 2016 by Ashish Kumar Khanna
...