reference to valueOf is ambiguous

自作多情 提交于 2019-12-11 21:12:10

问题


I came across: import static java.lang.Float.*;, note the static (actually it was import static java.lang.Math.* but that aside). I had never seen that before and thought it was very usefull, Float.valueOf("1.234f"); becomes valueOf("1.234f").

But when i added import static java.lang.Integer.*; also, i got an error message: "reference to valueOf is ambiguous" because both these classes have that (static) method.

Is there is no way around that? I can use this only a limited of times before its ambiguous somewhere?

On a sidenote:

Has this situation the same background as why we can only extend one class, because if we could extend two classes, for all the static fields etc, the naming could cause the same problems?


回答1:


As you note, you don't need to reference Float to access its static methods when you import it statically. But because both Float.valueOf(String string) and Integer.valueOf(String string) are available, how could the compiler know if you mean you want a Float value or an Integer value when you call valueOf(String string)?

The compiler only matches the method name and signature: a "valueOf" and a single string argument. It doesn't see that you have a decimal point and an f in your string: that's what valueOf does.

To resolve the ambiguity, call either Float.valueOf("1.234f") or Integer.valueOf("1234").




回答2:


Both classes are already imported for you, so just call the ambiguous method explicitly:

Float.valueOf(arg); // or Integer.valueOf(arg);



回答3:


Regarding the "side note": IMHO it would have been better to ask your side note in a new question, but to answer it: No, this is a very different thing. Java decided to not allow multiple inheritance to avoid the diamond problem.

  • C++ does allow it but it's one of the reasons why that language is considered complicated.
  • Scala does allow it too (called traits) and resolves the diamond problem by inheritance order to resolve issues. Read this good post explaining it.



回答4:


This is really no different than having 2 different classes with the same name (in different packages). Only 1 can be imported and the other must be referenced using the fully qualified name.



来源:https://stackoverflow.com/questions/29357723/reference-to-valueof-is-ambiguous

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!