Why does the compiler prefer an int overload to a varargs char overload for a char?

前端 未结 4 1153
清酒与你
清酒与你 2020-12-01 07:00

Code

public class TestOverload {

    public TestOverload(int i){System.out.println(\"Int\");}
    public TestOverload(char... c){System.out.println(\"char\"         


        
4条回答
  •  粉色の甜心
    2020-12-01 07:50

    Solid advice from Joshua Bloch (Effective Java, 2nd Ed):

    "only choose as arguments for an overloaded method those that have -radically- different types."

    An object with a radically different type is one that can not reasonably be cast into another of the argument types. Following this rule can potentially save you hours of debugging a mysterious error that can happen when the compiler chooses at compile time the method overloading that you did not expect.

    Your lines of code violate this rule and open the door for bugs:

    public TestOverload(int i){System.out.println("Int");}
    public TestOverload(char... c){System.out.println("char");}
    

    A char is interconvertible with an int and so the only way you can predict what will happen with the invocations is to go to the Java Language Specification and read the somewhat arcane rules about how overloadings are resolved.

    Luckily, this situation shouldn't need JLS research. If you have arguments that are not radically different from each other, probably the best option is to not overload. Give the methods different names so that there is no possibility for error or confusion on the part of anyone who may need to maintain the code.

    Time is money.

提交回复
热议问题