2

I just saw this C# question and wondered, if something similar could happen in Java. It can, with

class A<T> {
    A(Integer o) {...}
    A(T o) {...}
}

the call

new A<Integer>(43);

is ambiguous and I see no way how to resolve it. Is there any?

Community
  • 1
  • 1
maaartinus
  • 44,714
  • 32
  • 161
  • 320
  • Take a look at the `Builder Design Pattern`, `Factory Pattern` or similiar. Using the above-mentioned constructor would end in statements like `A a = new A(42);` which doesn't tell anything about what `42` actually is. A more clean approach concerning software design would be `A a = A.createWithCapacity(42);`. In addition this solves your ambiguity. – Marc-Christian Schulze Sep 26 '12 at 08:21
  • @coding.mof: I'm using these patterns a lot, but at the end they have to call a constructor. However, this can be solved easily e.g. by a dummy constructor argument as nobody cares how it looks like. I really can't recall what I wanted it for; maybe I was just being curious. – maaartinus Sep 26 '12 at 09:02

3 Answers3

3

You can drop the generics during construction (and suppress a warning):

A<Integer> a = new A(42);

or, less preferably use reflection (where again you'd have to suppress warnings)

Constructor<A> c = A.class.getDeclaredConstructor(Integer.class);
A<Integer> a = c.newInstance(42);
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2

Indeed, it is ambiguous, and so doesn't compile if you try new A<Integer>(new Integer(0)).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

Yes, members of a parameterized type JLS3#4.5.2 can end up in conflicts that are precluded in a normal class declaration(#8.4.8). It's pretty easy to come up with many examples of this kind.

And in Java, neither constructor in your example is more specific than the other, because there is no subtyping relation between T and Integer. see also Reference is ambiguous with generics

If method overloading creates this kind of ambiguity, we can usually choose to use distinct method names. But constructors cannot be renamed.


More sophistries:

If <T extends Integer>, then indeed T is a subtype of Integer, then the 2nd constructor is more specific than the 1st one, and the 2nd one would be chosen.

Actually javac wouldn't allow these two constructors to co-exist. There is nothing in the current Java language specification that forbids them, but a limitation in the bytecode forces javac to forbid them. see Type Erasure and Overloading in Java: Why does this work?

Another point: If <T extends Integer>, since Integer is final, T can only be Integer, so Integer must also be a subtype of T, therefore isn't the 2nd constructor also more specific than the 1st?

No. final isn't considered in subtyping relations. It is actually possible to drop final from Integer one day, and Java even specifies that removing final does not break binary compatibility.

Community
  • 1
  • 1
irreputable
  • 44,725
  • 9
  • 65
  • 93