java - How to define a generic List in an abstract super class? -
i'm trying create abstract class abstract method, should able return type of list items extending superbean
.
later want create generic class can add items lists. example:
class abstractservice<t extends superbean> { //this i'm aiming void add(t item) { // "is not applicable arguments (t)" superbean.getsublist().add(item); } } abstract class superbean { abstract list<? extends superbean> getsublist(); } class mybean1 extends superbean { list<mybean2> sublist; list<mybean2> getsublist() { return sublist; } } class mybean2 extends superbean { list<mybean3> sublist; list<mybean3> getsublist() { return sublist; } }
question: how have define abstract getsublist()
class can add t item
implementation of superbean
?
you need add generics in abstractservice
:
// add s t's type parameter add <s> superbean here class abstractservice<s extends superbean, t extends superbean<s>> { // i'm assuming superbean defined here. t superbean; //this i'm aiming void add(s item) { superbean.getsublist().add(item); } }
next, need make superbean
generic, subclasses defining generic type parameter <t>
:
abstract class superbean<t extends superbean> { // can define abstract method properly: abstract list<t> getsublist(); }
each subclass defines generic type parameter appropriately:
class mybean1 extends superbean<mybean2> { list<mybean2> sublist; list<mybean2> getsublist() { return sublist; } }
and mybean2
defined similarly:
class mybean2 extends superbean<mybean3> { list<mybean3> sublist; list<mybean3> getsublist() { return sublist; } }
this allows declare services follows:
abstractservice<mybean2, mybean1> service1 = new abstractservice<mybean2, mybean1>(); abstractservice<mybean3, mybean2> service2 = new abstractservice<mybean3, mybean2>();
Comments
Post a Comment