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.
- Erasure is a type of alteration in document. It can be classified as chemical erasure and physical erasure.
Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead.
Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.
What Is Type Erasure? Type erasure can be explained as the process of enforcing type constraints only at compile time and discarding the element type information at runtime. Therefore the compiler ensures type safety of our code and prevents runtime errors.
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.
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