Java: Generics in interface and factory -
i have base class plant there 2 subtype paths. fruit extends plant , vegetable extends plant. fruit , vegetable abstract classes , further have other classes banana extends fruit , spinach extends vegetable.
now lets example, operation has operation via these classes , there interface operation. current design follows:
i have interface:
abstract class plant {} abstract class fruit extends plant {} class banana extends fruit {} public interface plantweigher<t extends plant> { public int weight(t fruit); } then have:
public abstract class fruitweigher<y extends fruit> implements plantweigher<y> { } then further have concrete class:
public class bananaweigher extends fruitweigher<banana> { public int weight(banana fruit); } now, user understands plant, correct instance of weigher , perform operation.
so factory follows:
public class weigherfactory { public static plantweigher<? extends plant> getinstance(plant plant){ // based on logic on plant argument, return, lets say: return new bananaweigher(); } } so in user class, call following function:
plantweigher<? extends plant> instance = weigherfactory.getinstance(userplant); instance.weight(plant); // line gives error could 1 please me understand wrong design here , 1 please advice solution.
thanks.
the line :
plantweigher<? extends plant> instance = weigherfactory.getinstance(userplant); means, "i have weigher can weight subclass of plant, not kinds of plants". example, if factory return bananaweigher, wouldn't make sense try weight tomato this. achieve want should change factory follows:
public class weigherfactory{ public static <p extends plant> plantweigher<p> getinstance(p plant){ // should return correct weigher subttype of plant p return ... } } then calling code return like:
plantweigher<banana> instance =weigherfactory.getinstance(banana); instance.weigh(banana) now have specific plantweigher , can call specific type
or, if want able weigh kind of plant kind of plantweigher, should change latter:
public interface plantweigher { public int weight(plant p); } this ensures plantweigher can weight plan, wether makes sens or not.
Comments
Post a Comment