Home »
Java programming language
Java Observable notifyObservers() Method with Example
Observable Class notifyObservers() method: Here, we are going to learn about the notifyObservers() method of Observable Class with its syntax and example.
Submitted by Preeti Jain, on March 04, 2020
Observable Class notifyObservers() method
Syntax:
public void notifyObservers();
public void notifyObservers(Object o);
- notifyObservers() method is available in java.util package.
- notifyObservers() method is used to notify all of its observers in the list when the object has changed.
- notifyObservers(Object o) method is used to notify all of its observers in the list when this object has changed and later will invoke the clearChanged() to denotes that this object has no longer required to change.
- These methods don't throw an exception at the time of notifying an observer.
- These are non-static methods and it is accessible with the class object and if we try to access these methods with the class name then also we will get an error.
Parameter(s):
- In the first case, notifyObservers() – it does not accept any parameter.
- In the first case, notifyObservers(Object o) – Object o – represents an object of any type.
Return value:
In both the cases, the return type of the method is void, it returns nothing.
Example 1:
// Java program to demonstrate the example
// of notifyObservers() method of Observable
import java.util.*;
// Implement Observers class
class Observers_1 implements Observer {
public void update(Observable obj, Object ob) {
System.out.println("Obs1 is notified");
}
}
// Implement Observed Class
class Observed extends Observable {
// Function call with setChanged()
void notifyObserver() {
setChanged();
// By using notifyObservers() method is
// to notify all the observers that are
// implemented
notifyObservers();
}
}
public class NotifyObserver {
// Implement Main Method
public static void main(String args[]) {
Observed observed = new Observed();
Observers_1 obs1 = new Observers_1();
observed.addObserver(obs1);
observed.notifyObserver();
}
}
Output
Obs1 is notified
Example 2:
import java.util.*;
class Observers_2 implements Observer {
public void update(Observable obj, Object ob) {
System.out.println("Obs2 is notified: " + ((Float) ob).floatValue());
}
}
// Implement Observed Class
class Observed extends Observable {
// Function call with setChanged()
void notifyObserver1() {
setChanged();
// By using notifyObservers() method is
// to notify all the observers that are
// implemented
notifyObservers();
}
void notifyObserver2() {
setChanged();
// By using notifyObservers() method is
// to notify all the observers that are
// implemented with the given object
notifyObservers(new Float(10.0));
}
}
public class NotifyObserver {
// Implement Main Method
public static void main(String args[]) {
Observed observed = new Observed();
Observers_2 obs2 = new Observers_2();
observed.addObserver(obs2);
observed.notifyObserver2();
}
}
Output
Obs2 is notified: 10.0