简体   繁体   中英

Restated/simplified: Java generics involving overriding a method

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?

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
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM