Search code examples
javamethodsconstructorcallambiguous

Why do I get an ambiguous error when calling a Constructor inside of the same class in Java?


I can't figure out why i'm getting an ambiguous error. This is a sample code of what I have:

public class MyString{
    //Data:
    private char[] theString;
    //constructors:
    public MyString(){ // default constructor
    }
    public MyString(String s){ // parameterized constructor
    }
    public MyString(char[] s){ // parameterized constructor
    }
    public MyString(MyString s){ // copy constructor
    }
    //A method that calls a constructor:
    public MyString foobar(){
        return new MyString(theString);
    }
}

The above generates this error when foobar() is called from somewhere else:

./MyString.java:15: reference to MyString is ambiguous, both method MyString(char[])
in MyString and method MyString(theString) in MyString match
                return new MyString(theString);
              ^

Any ideas why?


Solution

  • I can't reproduce your error.

    But this kind of error basically happens when you try to call a function and the compiler doesn't have enough type information to determine which method to call.

    e.g. if you do:

    MyString tricky=new MyString(null);
    

    Then the compiler doesn't know whether null is meant to be a char[] or a String or a MyString, so you get an ambiguous error message.

    The usual way to fix this is to add an explicit cast, e.g.:

    MyString tricky=new MyString((String)null);
    

    Will work....