java – Overloaded constructor ambiguity – Education Career Blog

I’m trying to use an overloaded constructor in Java that can accept either an int or a String. I’m getting a compile error, which seems to be indicating that in this constructor call would be ambiguous if the variable were a null string, or a null array.

Is there an easy way around this?

,

Cast the argument to one of the types:

Foo f1 = new Foo((int) null);
// or
Foo f2 = new Foo((String) null);

,

The easiest way – avoid null. If it’s an empty String use ""; an empty int use new int.

To answer the question you can use a cast or assign null to a variable:

new MyClass((String)null)

final String nullString = null;
new MyClass(nullString)

The former is generally preferred, if you are going to do it at all.

,

maybe you can add a constructor without arguments.

,

If you have control of the class you wish to instantiate, consider using a static factory method so you can give them two separate names and avoid the overloading-related confusion.

public static Foo createFromIntArray(final int ints) { ... }
public static Foo createFromString(final String str) { ... }

Otherwise, decide what your null represents: Is it a null array of ints, or a null string? It’s possible that the class you are constructing behaves differently given one over the other. Once you know what your null represents, simply cast it to that type in the call to the constructor.

new Foo((String) null);
new Foo((int) null);

Lastly, it sounds like you might be passing an object reference to this constructor instead of an explicit null. Perhaps something you’re getting from a java.util.Map. If so, you could test this object with instanceof and cast to the appropriate type before sending it on to the constructor in question.

Leave a Comment