Reputation: 992
I'm using generics in Java for the first time, and I'm facing an issue I don't manage to overcome: why this compiles:
public interface Aa{}
public interface Bb{}
public interface Cc{}
public static <GenericAB extends Aa & Bb>
void method(GenericAB myABobject1, GenericAB myABobject2){}
public static <GenericAB extends Aa & Bb, GenericCA extends Cc & Aa>
void method(GenericAB myAbobject, GenericCA myCAobject){}
But this does not:
public interface Aa{}
public interface Bb{}
public interface Cc{}
public static <GenericAB extends Aa & Bb>
void method(GenericAB myABobject1, GenericAB myABobject2){}
public static <GenericAB extends Aa & Bb, GenericAC extends Aa & Cc>
void method(GenericAB myAbobject, GenericAC myACobject){}
And I get this error: both methods have same erasure.
I'm sorry if this is a stupid question, but I don't get why the order of interfaces in a bounded type parameter declaration seems to have importance. In reality I don't think it is the order which causes the error, but I don't get what does.
I'm reading this documentation by Oracle, it says which I must put the class as first parameter but Aa, Bb and Cc are all interfaces. Sorry for my english too.
Upvotes: 8
Views: 180
Reputation: 1010
Because at runtime after type erasure both of the methods have the same method header
public static <GenericAB extends Aa & Bb> void method(GenericAB myABobject1, GenericAB myABobject2){}
becomes
public static void method(Aa myABobject1, Aa myABobject2){}
and
public static <GenericAB extends Aa & Bb, GenericBC extends Aa & Cc>void method(GenericAB myAbobject, GenericBC myBCobject){}
becomes
public static void method(Aa myAbobject, Aa myBCobject){}
both resulting methods have the same signature which results in your error
EDIT after comments below parameters are fixed
Upvotes: 1
Reputation: 37845
It is the order that matters (§4.6):
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
GenericBC
erases to either Aa
or Cc
, depending on which appears first (i.e. leftmost) in the bound.
Also see type erasure tutorial and type erasure, when and what happens Q&A for explanations of type erasure in general.
Upvotes: 4