Java – generics – what am I missing or what’s the point?
I have the following code:
public class AClass<X extends AnInterface> implements AnotherInterface {
public AClass(X x){
}
}
Why do I use X as the constructor parameter type when I can replace it with aninterface? Of course, they mean the same. Is everything a subtype of aninterface?
I tried to keep all parameter types generic and only mentioned the interface name in the generic parameter declaration, such as "x extends aninterface", but I encountered a problem because it said that the value I passed in (type aninterface) was not equal to the input X
Edit:
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 encountered the problem. I got a compilation error, saying that the type of B is aninterface, and the required type in the constructor of aclass is X
Solution
If you declare such a variable:
private AClass<Foo> a;
The following are valid:
a = new AClass<Foo>(new Foo());
But the following are not:
a = new AClass<Foo>(new Bar());
(suppose Foo and bar are two implementations of aninterface)
In this case, this is generics: limiting types to specific types that implement (or extend) aninterface
