简体   繁体   中英

Java Method return Types from Inheritance

I'm writing a method in a class Parent that returns a set of some object A . However, I have a class Child (inheriting form Parent ). I want it to return a set of some object B ( B inheriting from A ).

More specifically, my methods looks something like this (it throws compile errors right now).

Parent class method:

public abstract <T extends A> Set<T> getSet();

Child class (extends Parent class) method:

public <T extends B> Set<T> getSet() {...}

Is it possible to do this, or does it not make sense?

First of all, let me explain why your code does not compile. Basically, if you have class A {} and class B extends A {} then Set<B> is not a sub-type of Set<A> . So if your parent method returns a Set<A> , your override must return the same thing. A Set<B> is a completely different type .

Likewise, Set<T extends B> is not a sub-type of Set<T extends A> . The full explanation is found in Java docs .

The closest solution that I can think of, uses wildcards:

class A {}

class B extends A {}

abstract class Parent {
    abstract Set<? extends A> getSet();
}

class Child extends Parent {
    Set<? extends B> getSet() {
        return new HashSet<B>();
    }
}

Set<? extends B> Set<? extends B> is a sub-type of Set<? extends A> Set<? extends A> , and this now works because of covariant return types (appreciate the comments from Lii & Marco13 below).

Depending on what you are trying to achieve exactly, this might be more limited than you expect, but is probably as close as it gets.

Perhaps something similar could be achieved using inner classes, as Jude said, but I don't see how that would be a more convenient solution.

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