Home » Java programming language

Java Observable hasChanged() Method with Example

Observable Class hasChanged() method: Here, we are going to learn about the hasChanged() method of Observable Class with its syntax and example.
Submitted by Preeti Jain, on March 04, 2020

Observable Class hasChanged() method

  • hasChanged() method is available in java.util package.
  • hasChanged() method is used to check whether this object has changed or not.
  • hasChanged() 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.
  • hasChanged() method does not throw an exception at the time of checking status.

Syntax:

    public boolean hasChanged();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is boolean, it returns true when this object has changed otherwise it returns false.

Example:

// Java program to demonstrate the example 
// of boolean hasChanged() 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 hasChange() {
        setChanged();

        // By using hasChanged() method is to
        // check that the observer is changed by using
        // setChanged() method or not
        System.out.println("setChanged(): " + hasChanged());
        notifyObservers();
    }
}

public class HasChanged {
    // Implement Main Method
    public static void main(String args[]) {
        Observed observed = new Observed();
        Observers obs = new Observers();
        observed.addObserver(obs);
        observed.hasChange();
    }
}

Output

setChanged(): true
Obs is added



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.