0

I have a (for me) complex Java generics problem. I've asked a similar question in stackoverflow before but came to the conclusion that this example made things overly complex. So, here the simplified question.

I have two classes as follows

abstract public class Base {
     abstract public Base doSomething(Base arg);
}

public class Variant extends Base {
     @Override
     public Variant doSomething(Variant arg) {  // <-- error
           // code
     }
}

The error message is "The method doSomething(Variant) of type Variant must override or implement a supertype method."

The selected answer in the initial question is to use generified versions class Base<T extends Base<T>> and class Variant<T extends Variant<T>> extends Base<T>, which works. But then, if I want to create an instance of Variant, I need to supply a generics parameter, even though I don't "need" one.

Is there a more simple solution?

Community
  • 1
  • 1
Ulrich Scholz
  • 2,039
  • 4
  • 30
  • 51

2 Answers2

4
abstract public class Base<T extends Base<T>> {
    abstract public T doSomething(T arg);
}

public class Variant extends Base<Variant> {
    @Override
    public Variant doSomething(Variant arg) {  // <-- error
        // code
    }
}
Anatoly Deyneka
  • 1,238
  • 8
  • 13
0

No vote please If you have function R f(P) then an overriden method f' may restrict R to a child, but could only restrict P to a super class whenever f is called.

Computer Science would say: a result type is co-variant, a parameter type is contra-variant (with respect to inheritance).

The solution of making P parametrizable in the base class is correct: @AnatolyDeyneka. For the internal logic R == P.

doSomething then not really can be that variable.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138