Observable class and the sample program in Java

By: Norman Chap Emailed: 1768 times Printed: 2517 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

To observe an observable object, you must implement the Observerinterface. This interface defines only the one method shown here:

void update(Observable observOb, Object arg)

Here, observOb is the object being observed, and arg is the value passed by notifyObservers(). The update() method is called when a change in the observed object takes place.

Here is an example that demonstrates an observable object. It creates an observer class, called Watcher, that implements the Observer interface. The class being monitored is called BeingWatched. It extends Observable. Inside BeingWatched is the method counter(), which simply counts down from a specified value. It uses sleep() to wait a tenth of a second between counts. Each time the count changes, notifyObservers() is called with the current count passed as its argument. This causes the update() method inside Watcher to be called, which displays the current count. Inside main(), a Watcher and a BeingWatched object, called observing and observed, respectively, are created. Then, observing is added to the list of observers for observed. This means that observing.update() will be called each time counter() calls notifyObservers().

/* Demonstrate the Observable class and the
Observer interface.
*/
import java.util.*;
// This is the observing class.
class Watcher implements Observer {
public void update(Observable obj, Object arg) {
System.out.println("update() called, count is " +
((Integer)arg).intValue());
}
}

//This is the class being observed.
class BeingWatched extends Observable {
void counter(int period) {
for( ; period >=0; period—) {
setChanged();
notifyObservers(new Integer(period));
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println("Sleep interrupted");
}
}
}
}

class ObserverDemo {
public static void main(String args[]) {
BeingWatched observed = new BeingWatched();
Watcher observing = new Watcher();
/* Add the observing to the list of observers for
observed object. */
observed.addObserver(observing);
observed.counter(10);
}
}

The output from this program is shown here:

update() called, count is 10
update() called, count is 9
update() called, count is 8
update() called, count is 7
update() called, count is 6
update() called, count is 5
update() called, count is 4
update() called, count is 3
update() called, count is 2
update() called, count is 1
update() called, count is 0

More than one object can be an observer. For example, the following program implements two observing classes and adds an object of each class to the BeingWatched observer list. The second observer waits until the count reaches zero and then rings the bell.

/* An object may be observed by two or more
observers.
*/
import java.util.*;
// This is the first observing class.
class Watcher1 implements Observer {
public void update(Observable obj, Object arg) {
System.out.println("update() called, count is " +
((Integer)arg).intValue());
}
}

// This is the second observing class.
class Watcher2 implements Observer {
public void update(Observable obj, Object arg) {
// Ring bell when done
if(((Integer)arg).intValue() == 0)
System.out.println("Done" + '\\7');
}
}

// This is the class being observed.
class BeingWatched extends Observable {
void counter(int period) {
for( ; period >=0; period—) {
setChanged();
notifyObservers(new Integer(period));
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println("Sleep interrupted");
}
}
}
}

class TwoObservers {
public static void main(String args[]) {
BeingWatched observed = new BeingWatched();
Watcher1 observing1 = new Watcher1();
Watcher2 observing2 = new Watcher2();
// add both observers
observed.addObserver(observing1);
observed.addObserver(observing2);
observed.counter(10);
}
}

The Observable class and the Observer interface allow you to implement sophisticated program architectures based on the document/view methodology. They are also useful in multithreaded situations.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(2)


1. View Comment

wow... and Thanks...

View Tutorial          By: lasitha at 2010-07-24 21:38:50
2. View Comment

thanks!!

View Tutorial          By: eoko at 2011-05-10 23:34:29

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Norman Chap
The break Statement example in Java
Stored Procedures example in SQL
JDBC and Tomcat context settings
File read and write - sample program in C
Pointers and Function Arguments in C
Writing the first Struts application
goto and labels in C
External Variables and Scope in C
Multiple inheritance example in C++
qsort() sample program in C++
Image and ImageItem sample program in J2ME
SimpleDateFormat sample program in Java
Observable class and the sample program in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
A Serialization Example in Java
Using One-Dimensional Arrays in Java
Method Overriding in Java
indexOf( ) and lastIndexOf( ) in Java
The java Buzzwords
Write to a file in Java - Sample Program
XML and Java - Parsing XML using Java Tutorial
Student marks calculation program in Java
Handling Fractions in Java
Calculate average sale of the week in Java
How to create an array and method in JSP
How to use set, get basic and nested properties for Spring framework
How to access instance from an inner class and accessing outer class variables in java
Converting a number into its equalant value in words in Java
What is Java?
Most Emailed Articles (in Java)
Converting a number into its equalant value in words in Java
java.lang.reflect package
Disadvantages of using Native methods in Java
What is UCS? What is ISO 10646?
Generating Your Key Pair example using keytool in Java
Operator Precedence in Java
PushbackReader sample program in Java
concat(), replace(), and trim() Strings in Java
instanceof sample program in Java
Use of - new - in Java
The Benefits of OOP
Increment and Decrement Operator
Characters in java
The continuing Revolution of java
Why java is important to the Internet