Andi Gu Andi Gu - 1 year ago 64
Java Question

Java Method return Types from Inheritance

I'm writing a method in a class

that returns a set of some object
. However, I have a class
(inheriting form
). I want it to return a set of some object
inheriting from

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

class method:

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

class (extends
class) method:

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

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

Answer Source

I am still not allowed to post comments, so forced to provide an answer...

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<T extends A> {
    abstract Set<? extends A> getSet();

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

Obviously, this is considerably more limited than your intended solution would have been, particularly because you now will be linked to class instances. However, since the latter is not exactly possible, this might be the next best thing.

Something similar could be achieved using inner classes, as Jude said, but those would not be static classes and I can't see how that would be a more convenient solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download