The Wayback Machine - https://web.archive.org/web/20240910033321/https://www.geeksforgeeks.org/java-util-observable-class-java/
Open In App

Java.util.Observable class in Java

Last Updated : 08 Jul, 2017
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

java.util.Observable is used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified. The update( ) method is called when an observer is notified of a change.

Note: Observing class must implement the Observer interface, which defines the update( ) method.

An object that is being observed must follow two simple rules :

  1. If it is changed, it must call setChanged( ) method.
  2. When it is ready to notify observers of this change, it must call notifyObservers( ) method. This causes the update( ) method in the observing object(s) to be called.
Be careful, if the object calls notifyObservers( ) method without having previously called
setChanged( ) method, no action will take place.

The observed object must call both setChanged( ) and notifyObservers( ) method, before update( ) will be called.
Constructor of java.util.Observable :

  • Observable( )
    Construct an Observable with zero Observers.

Methods:

  1. addObserver(Observer observer) : Adds observer to the list of objects observing the invoking object.
    Syntax : public void addObserver(Observer observer)
    Exception : NullPointerException -> if the parameter observer is null
    




    // Java code to demonstrate addObserver() method
    import java.util.*;
      
    // This is the observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer1 is added");
        }
    }
      
    // This is class being observed
    class BeingObserved extends Observable
    {
        void incre() 
        {
            setChanged();
            notifyObservers();
        }
    }
      
    class ObserverDemo {
        // Driver method of the program
        public static void main(String args[]) 
        {
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            beingObserved.addObserver(observer1);
            beingObserved.incre();
        }
    }

    
    

    Output :

    Observer1 is added
  2. setChanged() : Called when the invoking object has changed.
    Syntax : protected void setChanged( )
    Exception : NA.
    




    // Java code to demonstrate setChanged() method
    import java.util.*;
      
    // This is first observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) { }
    }
      
    // This is class being observed
    class BeingObserved extends Observable
    {
        void func1()
        {
            setChanged();
            System.out.println("Change status with setChanged :" + hasChanged());
            notifyObservers();
        }
          
        void func2()
        {
            System.out.println("Change status without setChanged :" + hasChanged());
            notifyObservers();
        }
    }
      
    class ObserverDemo {
        // Driver method of the program
        public static void main(String args[]) 
        {
            boolean status;
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            beingObserved.addObserver(observer1);
            beingObserved.func1();
            beingObserved.func2();
        }
    }

    
    

    Output :

    Change status with setChanged :true
    Change status without setChanged :false
  3. clearChanged(): Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change, so that the hasChanged( ) method will now return false.
    Syntax : protected void clearChanged( )
    Exception : NA
    




    // Java code to demonstrate clearChanged() method
    import java.util.*;
      
    // This is the observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Inside Observer1");
        }
    }
      
    // This is the class being observed
    class BeingObserved extends Observable
    {
        void func1()
        {
            setChanged();
            // clearChanged method removes all the changes made by setChanged method
            clearChanged();
            notifyObservers();
              
        }
    }
      
    class ObserverDemo {
    // Driver method of the program
        public static void main(String args[]) 
        {
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            beingObserved.addObserver(observer1);
            beingObserved.func1();
        }
    }

    
    

    Output :

    No Output

    No output is obtained because clearChanged( ) method has removed all the changes.

  4. notifyObservers() : Notifies all observers of the invoking object that it has changed by calling update( ).
    A null is passed as the second argument to update( ).

    Syntax : public void notifyObservers( )
    Exception : NA
    




    // Java code to demonstrate notifyObservers( ) method
    import java.util.*;
       
    // This is first observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer1 Notified");
        }
    }
      
    // This is second observer
    class Observer2 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer2 Notified");
        }
    }
      
    // This is class being observed
    class BeingObserved extends Observable
    {
        void func1()
        {
            setChanged();
            /*This method notifies the change to all the 
            observers that are registered*/
            notifyObservers();
              
        }
    }
      
    class ObserverDemo {
        // Driver method of the program
        public static void main(String args[]) 
        {
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            Observer2 observer2 = new Observer2();
            beingObserved.addObserver(observer1);
            beingObserved.addObserver(observer2);
            beingObserved.func1();
        }
    }

    
    

    Output :

    Observer2 Notified
    Observer1 Notified
  5. notifyObservers(Object obj) : Notifies all observers of the invoking object that it has changed by calling update( ).
    obj is passed as an argument to update( ).

    Syntax : public void notifyObservers(Object obj)
    Exception : NA
    




    // Java code to demonstrate notifyObservers(Object obj) method
    import java.util.*;
      
    // This is first observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer1 Notified with value : "
                    ((Integer)arg).intValue());
        }
    }
      
    // This is second observer
    class Observer2 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer2 Notified with value : "
                    ((Integer)arg).intValue());
        }
    }
      
    // This is class being observed
    class BeingObserved extends Observable
    {
        void func1()
        {
            setChanged();
            /*This method notifies the change to all the 
            observers that are registered and passes an object*/
            notifyObservers(new Integer(10));
              
        }
    }
      
    class ObserverDemo {
        // Driver method of the program
        public static void main(String args[]) 
        {
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            Observer2 observer2 = new Observer2();
            beingObserved.addObserver(observer1);
            beingObserved.addObserver(observer2);
            beingObserved.func1();
        }
    }

    
    

    Output :

    Observer2 Notified with value : 10
    Observer1 Notified with value : 10
  6. countObservers( ) : Returns the number of objects observing the invoking object.
    Syntax : public int countObservers( )
    Returns : the number of observers of this object
    Exception : NA
    




    // Java code to demonstrate countObservers() method
    import java.util.*;
      
    // This is first observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer1");
        }
    }
      
    // This is second observer
    class Observer2 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer2");
        }
    }
      
    // This is class being observed
    class BeingObserved extends Observable
    {
        void func1()
        {
            setChanged();
            notifyObservers();
        }
    }
      
    class ObserverDemo {
        // Driver method of the program
        public static void main(String args[]) 
        {
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            Observer2 observer2 = new Observer2();
            beingObserved.addObserver(observer1);
            beingObserved.addObserver(observer2);
            int count_observer = beingObserved.countObservers();
            System.out.println("Number of observers is " + count_observer);
            beingObserved.func1();
        }
    }

    
    

    Output :

    Number of observers is 2
    Observer2
    Observer1
  7. deleteObserver(Observer observer): Removes observer from the list of objects observing the invoking object.
    Passing null to this method will have no effect.

    Syntax : public void deleteObserver(Observer observer)
    Exception : NA
    




    // Java code to demonstrate deleteObserver(Observer observer) method
    import java.util.*;
      
    // This is first observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer1");
        }
    }
      
    // This is second observer
    class Observer2 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer2");
        }
    }
      
    // This is class being observed
    class BeingObserved extends Observable
    {
        void func1()
        {
            setChanged();
            notifyObservers();
        }
    }
      
    class ObserverDemo {
        // Driver method of the program
        public static void main(String args[]) 
        {
            int count_observer;
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            Observer2 observer2 = new Observer2();
            beingObserved.addObserver(observer1);
            beingObserved.addObserver(observer2);
              
            count_observer = beingObserved.countObservers();
            System.out.println("Number of observers before"
            " calling deleteObserver(): " + count_observer);
            beingObserved.func1();
              
            // Deleting observer1
            beingObserved.deleteObserver(observer1);
            count_observer = beingObserved.countObservers();
            System.out.println("No. of observers after"
            " calling deleteObserver(): " + count_observer);
            beingObserved.func1();
              
        }
    }

    
    

    Output :

    Number of observers before calling deleteObserver(): 2
    Observer2
    Observer1
    No. of observers aftercalling deleteObserver(): 1
    Observer2
  8. deleteObservers() : Removes all observers for the invoking object.
    Syntax : public void deleteObservers()
    Exception : NA
    




    // Java code to demonstrate deleteObservers() method
    import java.util.*;
      
    // This is first observer
    class Observer1 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer1");
        }
    }
      
    // This is second observer
    class Observer2 implements Observer
    {
        public void update(Observable obj, Object arg) 
        {
            System.out.println("Observer2");
        }
    }
      
    // This is class being observed
    class BeingObserved extends Observable
    {
        void func1()
        {
            setChanged();
            notifyObservers(new Integer(10));
        }
    }
      
    class ObserverDemo {
        // Driver method of the program
        public static void main(String args[]) 
        {
            int count_observer;
            BeingObserved beingObserved = new BeingObserved();
            Observer1 observer1 = new Observer1();
            Observer2 observer2 = new Observer2();
            beingObserved.addObserver(observer1);
            beingObserved.addObserver(observer2);
              
            count_observer = beingObserved.countObservers();
            System.out.println("Number of observers before"
            " calling deleteObserver(): " + count_observer);
            beingObserved.func1();
              
            // Deleting all observers
            beingObserved.deleteObservers();
            count_observer = beingObserved.countObservers();
            System.out.println("No. of observers after "
            "calling deleteObserver(): " + count_observer);
            beingObserved.func1();
              
        }
    }

    
    

    Output :

    Number of observers before calling deleteObserver(): 2
    Observer2
    Observer1
    No. of observers after calling deleteObserver(): 0

Ref: Observables in Java



Similar Reads

Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.jar.JarEntry class in Java
This class is used to represent a JAR file entry. Constructors : JarEntry(JarEntry je) : Creates a new JarEntry with fields taken from the specified JarEntry object. JarEntry(String name) : Creates a new JarEntry for the specified JAR file entry name. JarEntry(ZipEntry ze) : Creates a new JarEntry with fields taken from the specified ZipEntry objec
2 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.jar.JarInputStream class in Java
The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInputStream(InputStream in) : Creates a new JarInputS
3 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
Java.util.Locale Class in Java | Set 1
As the name suggests util.Locale Class is used to perform locale tasks and provides locale information for the user. Declaration : public final class Locale extends Object implements Cloneable, Serializable Constructors : Locale(String L): Creates Locale from the given language code.Locale(String L, String C): Creates Locale from the given language
4 min read
Java.util.Locale Class in Java | Set 2
Java.util.Locale Class in Java | Set 1 More methods: getDisplayVariant() : java.util.Locale.getDisplayVariant() displays variant of the Locale Syntax : public final String getDisplayVariant() Parameters : ---- Return : ----------- getDisplayVariant(Locale in) : java.util.Locale.Locale in(Locale in) returns the variant of "in" locale. Syntax : publi
3 min read
Java.util.Random class in Java
Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int. Constructors: Random(): Creates a new random number generator Random(
4 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schedules
3 min read
Java.util.Timer Class in Java
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer
6 min read
Java.util.ArrayDeque Class in Java | Set 1
java.util.ArrayDeque class describes an implementation of a resizable array structure which implements the Deque interface. Array deques has not immutable and can grow as necessary. They are not thread-safe and hence concurrent access by multiple threads is not supported unless explicitly synchronized. Null elements are invalid in this structure. M
5 min read
Java.util.ArrayDeque Class in Java | Set 2
Java.util.ArrayDeque Class in Java | Set 1 More Methods of util.ArrayDeque Class : 16. offer(Element e) : java.util.ArrayDeque.offer(Element e) : inserts element at the end of deque. Syntax : public boolean offer(Element e) Parameters : e - element to add Return : true, if element is added else; false 17. offerFirst(Element e) : java.util.ArrayDequ
5 min read
Java.util.Dictionary Class in Java
The java.util.Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and are used to access the values. It was part of the Java Collections Framework introduced in Java 1.2 but has been largely replaced by the java.util.Map interface since Java 1.2. The Dictionary class is an abstract cl
7 min read
Java.util.UUID class in Java
A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below). There are four differe
7 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handle NullPointerException and can also show customize
7 min read
Java.util.TimeZone Class | Set 1
TimeZone class is used to represents a time zone offset, and also figures out daylight savings.What is a Time Zone and Time Offset?"Time Zone" is used to describe the current time for different areas of the world. It refers to one of the specific regions out of the 24 total regions in the world that are divided up by longitude. Within each one of t
7 min read
Java.util.concurrent.Exchanger class with Examples
Exchanger is the most interesting synchronization class of Java. It facilitates the exchange of elements between a pair of threads by creating a synchronization point. It simplifies the exchange of data between two threads. Its operation is simple: it simply waits until two separate threads call its exchange() method. When that occurs, it exchanges
3 min read
Java.util.IntSummaryStatistics class with Examples
The IntSummaryStatistics class is present in java.util package. It takes a collection of Integer objects and is useful in the circumstances when we are dealing with a stream of integers. It maintains a count of the number of integers it has processed, their sum and various other statistics. The class can also be used with Streams. It is useful in t
3 min read
Article Tags :
Practice Tags :