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?
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.
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.
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.
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.
Cast the argument to one of the types:
Foo f1 = new Foo((int[]) null);
// or
Foo f2 = new Foo((String) null);
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