开发者

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 constru开发者_JAVA技巧ctor
    }
    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?


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....


Aha!! I found the problem. Lines 260 and 261 of my code were accidentally switched so the compiler was looking at my return function as a method.

It would be the equivalent of changing the above sample code to this erroneous version:

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); //THIS LINE WAS OUT OF PLACE! SHOULD BE IN FOOBAR!
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜