Search code examples
javaobserver-pattern

Call methods from observer


This should be really simple, but I can't get it to work.

//decreases the temperature automatically over time
Heating heating = new Heating(25);
//SHOULD watch when the temp drops below a threshold
Observer watcher = new Watcher();
heating.addObserver(watcher);

Heating has

public void turnOn()

and

public void turnOff()

it is no problem to print something to sysout when the threshold is reached

    class Watcher implements Observer {


    private static final int BOTTOM_TEMP = 23;

    @Override
    public void update(Observable o, Object arg) {

        double temp = Double.parseDouble(arg.toString());

        if (temp < BOTTOM_TEMP) {
            //System.out.println("This works! The temperature is " + temp);
            o.turnOn();  //doesn't work
            heater.turnOn();  //doesn't work either
        }
    }
}

So, in short: how do I call the turnOn() method of the observable from inside the observer? the above attempts result in "method undefined" and "heating cannot be resolved".

The methods are public, object exists and the observer is registered... what am I missing?


Solution

  • You need to cast Observable to Heating in order to call methods that are part of the Heating object. Like this:

    if (temp < BOTTOM_TEMP) {
      //System.out.println("This works! The temperature is " + temp);
      if (o instanceof Heating){
        ((Heating)o).turnOn(); 
      }
    }