I have a class CBound that implements two interfaces IBound1 and Ibound2:
class CBound implements IBound1, IBound2 {}
I have a generic method that accept as type parameter a class type that implements both IBound1 and Ibound2 interfaces:
public static <T extends IBound1 & IBound2> void getData(T list) {
//Some code...
}
I made an object of type IBound1 with the imlementation of CBound class:
IBound1 a = new CBound();
getData(a); // doesn't work
Why the obj a is not working as a parameter for getData() ?
When I change the code with :
CBound b = new CBound();
getData(b); // It works fine
The compiler has to infer a
Tthat satisfies the bounds at compile time.When you pass in
a, all that the compiler knows is thatais of typeIBound1. Since the method's parameter is alsoT, the compiler only really have two choices ofThere -IBound1orObject- neither of which satisfy the bounds.You might ask, "why doesn't the compiler infer
Tto beCBoundthen?" Well there isn't anything in the expressiongetData(a)that is of typeCBound. Even though we know thataactually refers to an object of typeCBoundby reading the previous lines of code, the compiler doesn't consider that when inferringT. And even ifTwere inferred to beCBound, you would not be able to passato a parameter of typeCBound.In the case of
bhowever, the compiler knows very well thatbis of typeCBound(because you have declared it so), so it can successfully inferTto beCBound.