Home » Java programming language

Java Observable deleteObserver() Method with Example

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

Observable Class deleteObserver() method

  • deleteObserver() method is available in java.util package.
  • deleteObserver() method is used to remove the given observer (obs) from the set of observers of this Observable object.
  • deleteObserver() 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.
  • deleteObserver() method does not throw an exception at the time of deleting an observer.

Syntax:

    public void deleteObserver(Observer obs);

Parameter(s):

  • Observer obs – represents the observer to be removed from the set.

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void deleteObserver(Observer obs) 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: ");
    }
}

class Observers_2 implements Observer {
    public void update(Observable obj, Object ob) {
        System.out.println("Obs2: ");
    }
}

// Implement Observed Class
class Observed extends Observable {
    // Function call
    void deleteObs() {
        setChanged();

        // By using notifyObservers() method is 
        // to notify all the observers that are
        // implemented
        notifyObservers();
    }
}

public class DeleteObservers {
    // Implement Main Method
    public static void main(String args[]) {
        Observed observed = new Observed();
        Observers_1 obs1 = new Observers_1();
        Observers_2 obs2 = new Observers_2();
        observed.addObserver(obs1);
        observed.addObserver(obs2);

        // By using countObservers() method is
        // to return the number of observers 
        // in this object
        int count_obs = observed.countObservers();
        System.out.println("observed.countObservers(): " + count_obs);
        observed.deleteObs();

        // By using deleteObserver() method is used
        // delete the given observer if exists
        observed.deleteObserver(obs2);
        count_obs = observed.countObservers();
        System.out.println("observed.deleteObserver(obs2): " + count_obs);
        observed.deleteObs();
    }
}

Output

observed.countObservers(): 2
Obs2: 
Obs1: 
observed.deleteObserver(obs2): 1
Obs1: 


Comments and Discussions!

Load comments ↻





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