I have the following code:
public class AClass<X extends AnInterface> implements AnotherInterface {
public AClass(X x){
}
}
Why would I use X as the constructor parameter type, when I could just replace this with AnInterface?? Surely they mean the same thing, anything which is a subtype of AnInterface?
I am trying to keep all my parameter types as generic and only mention Interface names in the generic parametric declarations eg “X extends AnInterface” but running into problems because it is saying the value I pass in, which is of type AnInterface, is not equal to type X.
EDITED:
public void<X extends AnInterface> myMethod(){
AnInterface b = new ADiffClass();
AnotherInterface a = new AClass(b);
}
public class ADiffClass<X extends AnInterface> implements AnInterface {
public ADiffClass(){
}
}
This is where I am having problems, I get a compile error saying that the type of b is AnInterface and the type required in the constructor of AClass is X.
If you declare a variable like this:
the following will be valid:
but the following wwon’t:
(assuming
FooandBarare two implementations ofAnInterface).That’s the point of generics in that case: restrict the type to a specific type that implements (or extends) AnInterface.