oop - Java Method return Types from Inheritance -
i'm writing method in class parent returns set of object a. however, have class child (inheriting form parent). want return set of object b (b inheriting a).
more specifically, methods looks (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 possible this, or not make sense?
first of all, let me explain why code not compile. basically, if have class {} , class b extends {} set<b> not sub-type of set<a>. if parent method returns set<a>, override must return same thing. set<b> completely different type.
likewise, set<t extends b> not sub-type of set<t extends a>. full explanation found in java docs.
the closest solution can think of, uses wildcards:
class {} class b extends {} abstract class parent { abstract set<? extends a> getset(); } class child extends parent { set<? extends b> getset() { return new hashset<b>(); } } set<? extends b> is sub-type of set<? extends a>, , works because of covariant return types (appreciate comments lii & marco13 below).
depending on trying achieve exactly, might more limited expect, close gets.
perhaps similar achieved using inner classes, jude said, don't see how more convenient solution.
Comments
Post a Comment