Java – why do generic types have the same signature?
I have the following generic classes:
class Or<A,B> { Or (A a) {} Or (B b) {} }
Why do I get the following errors when I try to compile:
Or(A) is already defined in Or Or (B b) ^
In my opinion, two constructors share the same signature, although they have different generic type parameters Why? And how to solve this problem?
to update
I understand the problem now The compiler needs a way to distinguish between these two types Adding such constraints is OK for my use case So I would like to add a question:
How do you specify that the two types of a and B may be different?
Solution
They are Signature is
Or(Object o);
Because of the implementation of 7000 generics in Java: references to generic types are converted to system. XML in all contexts where they are used Object; Generic types are known only to the compiler
Unfortunately, you cannot easily solve this problem in constructors You can replace overloaded constructors with factory methods and provide different names, such as orwitha and orwithb:
// Hide the constructor private Or(...) { ... } // Publish factory methods public static <X> Or OrWithA(X a) { return new Or(...); } public static <X> Or OrWithB(X a) { return new Or(...); }