Home » Java programming language

Java Observable countObservers() Method with Example

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

Observable Class countObservers() method

  • countObservers() method is available in java.util package.
  • countObservers() method is used to count the number of observers exists in this Observable.
  • countObservers() 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.
  • countObservers() method does not throw an exception at the time of counting the observer.

Syntax:

    public int countObservers();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is int, it gets the number of observers in this Observable.

Example:

// Java program to demonstrate the example 
// of int countObservers() 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 countObs() {
        setChanged();

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

public class CountObservers {
    // 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.countObs();
    }
}

Output

observed.countObservers(): 2
Obs2: 
Obs1: 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.