I have a generic class with this definition:
public class AcoProblemSolver<C, E extends Environment, A extends AntColony<E, Ant<C, E>>> {
Where AntColony
goes this way:
public abstract class AntColony<E extends Environment, A extends Ant<?, E>> {
And Ant
goes like this:
public abstract class Ant<C, E extends Environment> {
I was hoping to extend AntColony
in this fashion:
public class FlowShopProblemSolver extends
AcoProblemSolver<Integer, FlowShopEnvironment, FlowShopAntColony> {
But Eclipse is showing an error on the FlowShopAntColony
parameter class:
Bound mismatch: The type FlowShopAntColony is not a valid substitute for the bounded parameter <A extends AntColony<E,Ant<C,E>>> of the type AcoProblemSolver<C,E,A>
Which confuses me, since FlowShopAntColony
is defined this way:
public class FlowShopAntColony extends
AntColony<FlowShopEnvironment, AntForFlowShop> {
And AntForFlowShop
goes like this:
public class AntForFlowShop extends Ant<Integer, FlowShopEnvironment> {
Why isn't FlowShopAntColony
accepted as a valid parameter?
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
A bound is a constraint on the type of a type parameter. Bounds use the extends keyword and some new syntax to limit the parameter types that may be applied to a generic type. In the case of a generic class, the bounds simply limit the type that may be supplied to instantiate it.
A extends AntColony<E, Ant<C, E>>
The third parameter of AcoProblemSolver
has the restriction extends AntColony<E, Ant<C, E>>
. The second parameter of AntColony
must be exactly Ant<C, E>
and you're trying to pass a subclass of Ant
. Try:
A extends AntColony<E, ? extends Ant<C, E>>
You may want other similar ? extends
clauses elsewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With