When varargs started to not conflict with no-arg?

百般思念 提交于 2019-12-11 04:04:14

问题


Today I found that the following code compiles and runs with no any warning:

public class Try_MultipleArguments2 {

    public static void main(String[] args) {

        myfunction();

        myfunction(1, 2, 3);

    }

    public static void myfunction(int ... as) {
        System.out.println("varags called");
    }

    public static void myfunction() {
        System.out.println("noarg called");
    }
}

I am remembering clear, that it was not so earlier.

Is this JVM change or my memory glitch???

How it distinguish between no-arg and varargs?

UPDATE

The following code also runs ok:

public class Try_MultipleArguments2 {

    public static void main(String[] args) {

        myfunction();

        myfunction(1, 2, 3);

    }

    public static void myfunction(int ... as) {
        System.out.println("varags called");
    }

//    public static void myfunction() {
//        System.out.println("noarg called");
//    }
}

回答1:


These are overloaded methods. The compiler knows which method the compiled main shoulld call from the method signature. See this specification:

When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2).

Furthermore, the method chosen is the one that is most specific. See this. In this case, the no-arg method is more specific than the varargs version - again the number of parameters is checked to see which method to choose..




回答2:


Its function overloading at backend.

Your void myfunction(int ... as) is accepting multiple arguments while your void myfunction() has no argument. I don't see any glitch in this . Method Overloading



来源:https://stackoverflow.com/questions/31201196/when-varargs-started-to-not-conflict-with-no-arg

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