Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded constructor ambiguity

Tags:

java

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?

like image 590
Eric Wilson Avatar asked Apr 06 '09 09:04

Eric Wilson


People also ask

How do you fix ambiguous call of overloading?

There are two ways to resolve this ambiguity: Typecast char to float. Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter.

What is ambiguity in constructor in C++?

ambiguous means the compiler found multiple “valid” choices and refused to make the choice for you. You need to add clarifying information (usually about types). It may be that the compiler is able to convert a value into a type that matches a constructor and can do this twice.

What does it mean when a constructor is overloaded?

Constructor overloading in Java refers to the use of more than one constructor in an instance class. However, each overloaded constructor must have different signatures. For the compilation to be successful, each constructor must contain a different list of arguments.

How can we prevent constructor overloading?

If possible, chain the constructors together so that the default for any particular value is only specified in one place - or use a constant. That way you get consistency.


1 Answers

Cast the argument to one of the types:

Foo f1 = new Foo((int[]) null);
// or
Foo f2 = new Foo((String) null);
like image 101
Joachim Sauer Avatar answered Sep 30 '22 22:09

Joachim Sauer