Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java PushbackReader Class
Next article icon

Java Observable Class

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the Observable class is used to create objects that can be observed by other parts of the program. When an object of such a subclass undergoes a change, observing classes are notified. The update() method is called when an observer is notified of a change.

Note: The Observable class and Observer interface are deprecated in Java 9.

Key Concepts:

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

  • The Observed Object:
    • If it is changed, it must call the setChanged() method.
    • When it is ready to notify observers of this change, it must call the notifyObservers() method. This triggers the the method in the observer objects.

Note: Be careful, if the object calls the notifyObservers() method without having previously called the setChanged() method, no action will take place.

  • The Observer Class:
    • The observer class implements the Observer interface and must override the update() method.

Constructors in Observable Class

This class consists of one constructor, with the help of which we can create objects of this class.

1. Observable( ): Construct an Observable with zero Observers.

Syntax:

Observable( )

Java Observable Methods

Now, we are going to discuss each method one by one in detail:

1. addObserver(Observer observer): Adds observer to the list of objects observing the invoking object.

Syntax:

public void addObserver(Observer observer)

  • Parameter: This method take single parameter Observer observer, which is an object that will notify for any changes.
  • Return Type: This method does not return anything.

Example:

Java
// Java program  to demonstrate  // the working of 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 Geeks{          // Driver method of the program     public static void main(String args[])     {         BeingObserved beingObserved = new BeingObserved();         Observer1 o1 = new Observer1();         beingObserved.addObserver(o1);         beingObserved.incre();     } } 

Output
Observer1 is added 


2. setChanged(): This method is used to marks the invoking object as changed.

Syntax:

protected void setChanged()

  • Parameter: This method does not return anything.
  • Return Type: This method does not take any parameter.

Note: Once setChanged() is called, the object let itsw observer know that something has changed.

Example:

Java
// Java program to demonstrates // the working of 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 Geeks {          // Driver method of the program     public static void main(String args[])     {         boolean status;         BeingObserved bo = new BeingObserved();         Observer1 o = new Observer1();         bo.addObserver(o);         bo.func1();         bo.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( )

  • Parameter: This method does not take any parameter
  • Return Type: This method does not return anything.

Example:

Java
// Java program to demonstrates the  // working of 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 Geeks {          // Driver method of the program     public static void main(String args[])     {         BeingObserved bo = new BeingObserved();         Observer1 o1 = new Observer1();         bo.addObserver(o1);         bo.func1();     } } 

Output:

No Output

Note: 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( )

  • Parameter: This method does not take any parameter.
  • Return Type: This method does not return anything.

Example:

Java
// Java program to demonstrates // the working of 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 Geeks {          // Driver method of the program     public static void main(String args[])     {         BeingObserved bo = new BeingObserved();         Observer1 o1 = new Observer1();         Observer2 o2 = new Observer2();         bo.addObserver(o1);         bo.addObserver(o2);         bo.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)

  • Parameter: This method does not take any parameter.
  • Return Type: This method does not return anything.

Example:

Java
// Java program to demonstrate the working of // 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();                  // Using Integer.valueOf          notifyObservers(Integer.valueOf(10));     } }  class Geeks {          // Driver method of the program     public static void main(String args[]) {         BeingObserved bo = new BeingObserved();         Observer1 observer1 = new Observer1();         Observer2 observer2 = new Observer2();         bo.addObserver(observer1);                  // Corrected variable name         bo.addObserver(observer2);                  // Calling func1 on the correct object         bo.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( )

  • Parameter: This method does not take any parameter.
  • Return Type: This method returns the number of observers currently observing the object.

Example:

Java
// Java program to demonstrates the  // working of 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 Geeks{          // Driver method of the program     public static void main(String args[])     {         BeingObserved bo = new BeingObserved();         Observer1 o1 = new Observer1();         Observer2 o2 = new Observer2();         bo.addObserver(o1);         bo.addObserver(o2);         int count_observer = bo.countObservers();         System.out.println("Number of observers is "          + count_observer);         bo.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)

  • Parameter: This method does not take any parameter.
  • Return Type: This method does not return anything.

Example:

Java
// Java code to demonstrate the working of // 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 Geeks {          // Driver method of the program     public static void main(String args[])     {         int c;         BeingObserved bo = new BeingObserved();         Observer1 observer1 = new Observer1();         Observer2 observer2 = new Observer2();         bo.addObserver(observer1);         bo.addObserver(observer2);          c = bo.countObservers();         System.out.println("Number of observers before" +                 " calling deleteObserver(): " + c);         bo.func1();          // Deleting observer1         bo.deleteObserver(observer1);         c = bo.countObservers();         System.out.println("No. of observers after"+                 " calling deleteObserver(): " + c);         bo.func1();      } } 

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


8. deleteObservers(): Removes all observers for the invoking object.

Syntax:

public void deleteObservers()

  • Parameter: This method does not take any parameter.
  • Return Type: This method does not return anything.

Example:

Java
// Java program to demonstrates the // working of 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( Integer.valueOf(10));     } }  class Geeks {          // Driver method of the program     public static void main(String args[])     {         int c;         BeingObserved bo = new BeingObserved();         Observer1 o1 = new Observer1();         Observer2 o2 = new Observer2();         bo.addObserver(o1);         bo.addObserver(o2);          c = bo.countObservers();         System.out.println("Number of observers before" +                 " calling deleteObserver(): " + c);         bo.func1();          // Deleting all observers         bo.deleteObservers();         c = bo.countObservers();         System.out.println("No. of observers after "+                 "calling deleteObserver(): " + c);         bo.func1();      } } 

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


Next Article
Java PushbackReader Class

D

Dipak Chouhan
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Java Reader Class
    Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must ext
    7 min read
  • Object Class in Java
    Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
    8 min read
  • Java Writer Class
    Java writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will u
    5 min read
  • LabelValue Class in JavaTuples
    A LabelValue is a Tuple from JavaTuples library that deals with only 2 elements - a label and a value. Since this LabelValue is a generic class, it can hold any type of value in it. Since LabelValue is a Tuple, hence it also has all the characteristics of JavaTuples: They are TypesafeThey are Immuta
    5 min read
  • Java PushbackReader Class
    The PushbackReader class in Java is part of the java.io.package, and is used for reading characters from a stream. This class lets us push characters back into the stream. Features of PushbackReader Class: This class uses a buffer that allows us to push characters back into the stream.This class is
    6 min read
  • Wrapper Classes in Java
    A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
    6 min read
  • Static class in Java
    Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
    3 min read
  • Generic Servlet Class
    GenericServlet implements the Servlet interface and provides an implementation for all its method except the service() method hence it is abstract. GenericServlet class defines a protocol-independent(HTTP-less) servlet. However, while building a website or an online application, we may want to have
    3 min read
  • Local Inner Class in Java
    Prerequisites: Nested Classes in Java Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop or an if clause. Local Inner classes are not a member of any enclosing classes. They belong to the block the
    5 min read
  • Nested Classes in Java
    In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences