1

Pretty trivial Java question. This code has an error:

public abstract class SubTypeDependentEditor<T> implements Editor<T> {
  protected abstract Editor<? extends T> getEditorFor(T obj);       

  public void edit(T obj) {
    Editor<? extends T> editor = getEditorFor(obj);
    editor.edit(obj); // ERROR IS HERE
  }
}

What's the right way one should fix it?

The idea of T is basically just a type of classes' hierarchy root, so given a hierarchy like this:

class Entity {}
class EntityA extends Entity {}
class EntityB extends Entity {}

one will have T set to Entity and getEditorFor(T obj) is responsible for returning Editor<X> where X depends on obj's concrete type and always Is-A T. So, if you have SubTypeDependentEditor<Entity>, getEditorFor(T obj) returns Editor<EntityA> when obj is EntityA and Editor<EntityB> when obj is EntityB.

Any chance this can be implemented without warnings?

Update:

protected abstract Editor<? extends T> getEditorFor(T obj);     

Can basically have any other signature, but the code that implements that code only has objects that are Editor<X>, so in case this method returns Editor<T> I'm not sure how to implement getEditorFor(T obj).

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
Andrey Agibalov
  • 7,624
  • 8
  • 66
  • 111

1 Answers1

4
protected abstract Editor<? extends T> getEditorFor(T obj);

means that getEditorFor() returns an editor for an unknown sub-type of T.

You can't pass use any value of type T with that result since the compiler cannot prove that obj works with the same concrete sub-type of T that is obj's type.

The solution is to change

protected abstract Editor<? extends T> getEditorFor(T obj);

to

protected abstract Editor<? super T> getEditorFor(T obj);

which says that getEditorFor returns an editor that edits an unknown type that includes obj.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245