2

I want to override a method that has an parameter of type Object:

public void setValue(Object value) {
    // ...
}

and make that parameter to have a generic type T:

@Override
public void setValue(T value) {
    super.setValue(value);
}

How can I do this in Java?

In Eclipse I get these errors:

Multiple markers at this line
- The type parameter T is hiding the type T
- Name clash: The method setValue(T) of type TextField<T> has the 
 same erasure as setValue(Object) of type JFormattedTextField but does not 
 override it
- The method setValue(T) of type TextField<T> must override or 
 implement a supertype method
Jonas
  • 121,568
  • 97
  • 310
  • 388
  • This might be what you're looking for http://stackoverflow.com/questions/239645/overriding-a-method-with-generic-parameters-in-java – loosebazooka Nov 29 '11 at 23:57
  • You can't make an overriding method accept a narrower type than the method it overrides, period. – millimoose Nov 30 '11 at 00:36

2 Answers2

5

You can't make an overriding method accept a narrower type than the method it overrides.

If you could, the following would be possible:

class A {
    public setValue(Object o) {…}
}

class B<T> extends A {
    @Override
    public setValue(T o) {…};
}

A a = new B<String>(); // this is valid
a.setValue(new Integer(123)); // this line would compile, but make no sense at runtime 
millimoose
  • 39,073
  • 9
  • 82
  • 134
  • 1
    But why wouldn't `a.setValue(new Integer(123));` work, since `Integer` inherit from `Object`? – Jonas Nov 30 '11 at 00:52
  • @Jonas: Because the variable `a` holds an object of type `B`, and the overriding method in `B` would get called. The type of the variable doesn't matter for method binding, the type of the object it stores does. – millimoose Nov 30 '11 at 00:53
-2

Use:

<T extends Object> public void setValue(T o) {…};

Then there will be no problem with a.setValue(new Integer(123));. Just define as A a = new B(); You can make this more narrow by replacing Object with the desired class.

  • This doesn't work: `Multiple markers at this line - Syntax error on token "public", delete this token - The method setValue(T) of type TextField must override or implement a supertype method - Name clash: The method setValue(T) of type TextField has the same erasure as setValue(Object) of type JFormattedTextField but does not override it` – Jonas Nov 30 '11 at 10:10
  • 1
    No, it doesn't work. And your method signature is wrong. It should return `void`. – Jonas Nov 30 '11 at 10:20
  • As for me, using instead of simple helped. +1 – Gangnus Feb 29 '12 at 07:47