以下类重载了方法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
}
}
问题是,调用的int方法!
如何打印在Test1
上?如何确定 5 是 int
而不是 short
?
最佳答案
编译器在编译时做出此决定。它标识所提供参数的类型;然后它会搜索最佳匹配。
因此:5的类型是int;因此,编译将对 calculate(int)
的调用放入字节码中。使用强制转换,您基本上可以指示编译器选择calculate(short)
。
需要理解的重要一点是,重载仅在编译时发生。这在支持动态调度的语言中有所不同 - 在此类语言中,“最合适”的类型是在运行时确定的。正如 Seelenvirtuose 所评论的:“面向对象设计”和多态的整个思想是重写是动态的!因此,清楚地区分两者非常重要;因为重载是编译时的;并且覆盖是运行时!
关于java - 方法重载 int 与 Short,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303872/