方法重载int vs short

Bhu*_*han 0 java polymorphism overloading

下面的类有重载方法calculate.第一种方法接受int,第二种方法接受short.

public class TestOverLoading
{
    public void calculate(int i)
    {
        System.out.println("int method called!");
    }

    public void calculate(short i)  //or byte
    {
        System.out.println("short method called!");
    }

    public static void main(String args[])
    {
        //Test1
        new TestOverLoading().calculate(5); //int method called

        //Test2         
        new TestOverLoading().calculate((short) 5); //short method called
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是如何int method called!打印Test1?它是如何确定5是int不short?

Gho*_*ica 5

编译器在编译时做出此决定.它标识提供的参数的类型; 然后它搜索最佳匹配.

因此:5的类型是int; 因此编译将调用calculate(int)放入字节码.使用强制转换,您基本上可以指示编译器选择calculate(short).

需要了解的重要一点是,重载只是编译时间.这与支持动态调度的语言不同- 在这种语言中,"最佳拟合"类型是在运行时确定的.正如Seelenvirtuose所评论的那样:"OO设计"和多态性的整个想法是压倒一切是动态的!因此,明确区分两者是很重要的; 因为重载是编译时的; 并且覆盖是运行时!