I have wrote this program in eclipse and eclipse is complaining that constructor is ambigious. I am not sure why java compiler calling them ambiguous.
public class Ambigious {
public Ambigious(float[] a){
System.out.println("array constructor");
}
public Ambigious(Integer a){
System.out.println("Integer constructor");
}
public static void main(String[] args) {
new Ambigious(null);
}
}
but this is not
public class Ambigious {
public Ambigious(Object a){
System.out.println("object constructor");
}
public Ambigious(float[] a){
System.out.println("array constructor");
}
public static void main(String[] args) {
new Ambigious(null);
}
}
Problem 1:
Both float[]
and Integer
are Objects so null
can be applied to both constructors.
Since there isn't any best suited type compiler can't decide which one should be used.
Problem 2:
In case of Object
and Integer
types the most suited one is chosen. For instance if you would pass new Integer(1)
as argument then both constructors could be applied because Integer
is also Object
, but compiler binds this invocation with code from constructor with most precise argument types.
Similarly with null
, since it can be used as Object
and Integer
compiler assumes that the more precise type would be Integer
.
To solve this kind of problems you can specify which type null
should represent by casting
new Ambigious((Integer)null);
You can also try changing one of argument types to non-Object like
public Ambigious(int a){//primitive type
instead of
public Ambigious(Integer a){
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