0

I'm developing a system where widgets listen for changes in some model. I wanted to notify widgets over an interface parametrized with notification's class. Why doesn't Java allow this:

public class UiInventory extends Widget implements 
    Observer<EventGetItem>, 
    Observer<EventLoseItem>, 
    Observer<EventWield>, 
    Observer<EventUnwield>, 
    Observer<EventPutOn>, 
    Observer<EventTakeOff> {

The error message is simply Duplicate class: 'my.package.structure.Observer', but why does it appear in the first place?

gvlasov
  • 18,638
  • 21
  • 74
  • 110

2 Answers2

6

The answer lies in Java's type erasure. At runtime, generic type information is erased, and this would just result in

public class UiInventory extends Widget implements 
  Observer, 
  Observer, 
  Observer, 
  Observer, 
  Observer, 
  Observer {

which you cannot do. Any generic type parameters in methods would resolve to Object and you'd get duplicate method signatures.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

Lets say that compiler would let you implement your interface few times

interface MyInterface<T>{
   T getValue();
}

class MyClass implements MyInterface<Integer>, MyInterface<String>{
    ??? getValue(){

    }
}

What type of value should be returned in getValue? Integer? String?

Even if your interface wouldn't have any generics methods then because of type erasure your class would be compiled into

class MyClass implements MyInterface, MyInterface{//no <Inger> or <String> here

}

which doesn't really have any point.

Pshemo
  • 122,468
  • 25
  • 185
  • 269