Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "The constructor ... is ambiguous" mean?

Tags:

I would like to know what the error message in Eclipse means:

The constructor Case(Problem, Solution, double, CaseSource) is ambiguous

like image 503
karikari Avatar asked Apr 12 '11 13:04

karikari


People also ask

What does it mean when the constructor is undefined?

this compilation error is caused because the super constructor is undefined. in java, if a class does not define a constructor, compiler will insert a default one for the class, which is argument-less. if a constructor is defined, e.g. super(string s), compiler will not insert the default argument-less one.

What is the sole purpose of constructors?

The purpose of constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code. Constructors cannot be abstract, final, static and synchronised while methods can be.


2 Answers

The problem exists when you try to instantiate a class that could apply to more than one constructor.

For example:

public Example(String name) {     this.name = name; }  public Example(SomeOther other) {     this.other = other; }  

If you call the constructor with a String object, there's one definite constructor. However, if you instantiate new Example(null) then it could apply to either and is therefore ambiguous.

The same can apply to methods with similar signatures.

like image 133
Michael Avatar answered Sep 19 '22 13:09

Michael


To add on to other answers, it can be avoided by casting the argument to what is intended, e.g.:

class Foo {      public Foo(String bar) {}     public Foo(Integer bar) {}      public static void main(String[] args) {         new Foo((String) null);     }  } 
like image 22
TheCoffeeCup Avatar answered Sep 19 '22 13:09

TheCoffeeCup