Andi Gu Andi Gu - 22 days ago 5
Java Question

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?

Answer

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: http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html.

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.

Comments