ObservedObject.java Source code

Java tutorial

Introduction

Here is the source code for ObservedObject.java

Source

import java.util.Observable;
import java.util.Observer;

class ObservedObject extends Observable {
    private String watchedValue;

    public ObservedObject(String value) {
        watchedValue = value;
    }

    public void setValue(String value) {
        if (!watchedValue.equals(value)) {
            System.out.println("Value changed to new value: " + value);
            watchedValue = value;

            setChanged();
            notifyObservers();
        }
    }
}

class MainObserver implements Observer {

    public void update(Observable obj, Object arg) {
        System.out.println("Update called");
    }
}

public class Main {

    public static void main(String[] args) {
        ObservedObject watched = new ObservedObject("Original Value");
        MainObserver watcher = new MainObserver();

        watched.addObserver(watcher);
        watched.setValue("New Value");
    }

}