Search code examples
javaobserver-pattern

Making a subclass observable in java


I have a subclass called Passenger which is extending from a Person class. I want to make the Passenger class a observable object. So I do it in this way,

class Person extends Observable{    
}

class Passenger extends Person{
    public void move(){
        setChanged();
        notifyObservers();
    }   
}

class Manager implements Observer{
    @Override
    public void update(Observable o, Object arg) {
    }  
}

Is it a bad practice to make the Person class Observable when I don't need observable functionality for that class? If so how can I change this?


Solution

  • I think the Obervable class in java is a fairly poorly thought out class. It really wants to be in interface in my opinion.

    However instead of having Person extend from Observable you can use composition at the Passenger level.

    Inside your Passenger class you could have code along the lines of this :

    private Observable observable = new Observable();
    
    public void addObserver(Observer o) {
        observable.addObserver(o);
    }
    
    public void notifyObservers() {
        observable.notifyObservers();
    }
    

    This is a compositional relationship to an observable object. It should work perfectly fine.

    More information in this question :

    Why is java.util.Observable not an abstract class?