Home »
Java programming language
Java Observable setChanged() Method with Example
Observable Class setChanged() method: Here, we are going to learn about the setChanged() method of Observable Class with its syntax and example.
Submitted by Preeti Jain, on March 04, 2020
Observable Class setChanged() method
- setChanged() method is available in java.util package.
- setChanged() method is used to set this Observable object status as changed.
- setChanged() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- setChanged() method does not throw an exception at the time of set changing status.
Syntax:
protected void setChanged();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is void, it returns nothing.
Example:
// Java program to demonstrate the example
// of void setChanged() method of Observable
import java.util.*;
// Implement Observers class
class Observers implements Observer {
public void update(Observable obj, Object ob) {
System.out.println("Obs is added");
}
}
// Implement Observed Class
class Observed extends Observable {
// Function call with setChanged()
void setChange() {
setChanged();
System.out.println("setChanged(): " + hasChanged());
notifyObservers();
}
// Function call without setChanged()
void unsetChange() {
System.out.println("unsetChanged(): " + hasChanged());
notifyObservers();
}
}
public class SetChanged {
// Implement Main Method
public static void main(String args[]) {
Observed observed = new Observed();
Observers obs = new Observers();
observed.addObserver(obs);
observed.setChange();
observed.unsetChange();
}
}
Output
setChanged(): true
Obs is added
unsetChanged(): false