Gravatar of Jeroen Jeroen Pelgrims

Java doesn't support inheriting twice from the same interface with a different generic parameter

Posted on in java, software-development

I created this:

public class Observable <T> {
  private List<Observer<T>> observers = new ArrayList<Observer<T>>();

  public void addObserver(Observer<T> observer){
    observers.add(observer);
  }

  public void removeObserver(Observer<T> observer){
    observers.remove(observer);
  }

  public void removeAllObservers(){
    observers.removeAll(observers);
  }

  public void notifyObservers(Observable<T> observable){
    for(Observer<T> observer : observers){
      observer.update(observable);
    }
  }
}

And this:

public interface Observer <T> {
  void update (Observable<T> observable);
}

So I could do this:

public class SomeClass implements Observer<SomeObservableA>, Observer<SomeObservableB>{
  @override
  public void update(Observable<SomeObservableA> observable){
    //do stuff for Observable A
  }

  @override
  public void update(Observable<SomeObservableB> observable){
    //do stuff for Observable B
  }
}

But apparently java only takes into account the class you're implementing and not the extra generics you're adding. So I ended up doing it this way (using the standard Observer and Observable):

public class SomeClass implements Observer{
  @Override
  public void update(Observable o, Object arg) {
    if(o instanceof SomeObservableA){
      //do stuff for Observable A
    }

    if(o instanceof SomeObservableB){
      //do stuff for Observable B
    }
  }
}

This post is written by Jeroen Pelgrims, an independent software developer who runs Digicraft.eu.

Hire Jeroen