4

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?

chamathabeysinghe
  • 858
  • 2
  • 13
  • 34
  • If you need to extend Passenger from Person there's no other way you could achieve what you are doing ;) – ParkerHalo Dec 03 '15 at 13:54
  • If you want to "make the Passenger class a observable object" why not have `Passenger` extend `Observable` indeed? – Peter Lawrey Dec 03 '15 at 14:06
  • 1
    cos it needs to extend person – Oliver Watkins Dec 03 '15 at 14:06
  • I agree with TangledUpInBlue (answer below). It seems reasonable to maker Person an interface. Then you can make two abstract classes; BasePerson and BaseObservablePerson to extend as needed. – DwB Dec 03 '15 at 14:21

2 Answers2

4

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?

Community
  • 1
  • 1
Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
0

You could also make the Person class an interface, so the Passenger class could extend Observable and implement Person. Just a thought.

TangledUpInBlue
  • 746
  • 4
  • 13