方法重载 int 与 short
method overloading int vs short
以下 class 有重载方法 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 method called!
如何打印在 Test1
上?如何确定5是int
而不是short
?
编译器在编译时做出这个决定。它标识提供的参数的类型;然后搜索最佳匹配项。
因此:5的类型是int;因此,编译将对 calculate(int)
的调用放入字节码中。使用强制转换,您基本上指示编译器改为 select calculate(short)
。
需要理解的重要一点是 重载 只是编译时。这在支持 动态调度 的语言中有所不同 - 在这些语言中,"best fitting" 类型在 运行 时确定。正如 Seelenvirtuose 评论的那样:"OO design" 和 多态性 的整个想法是 overriding 是动态的!因此,清楚地区分两者很重要;因为重载是编译时的;最重要的是 运行-time!
以下 class 有重载方法 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 method called!
如何打印在 Test1
上?如何确定5是int
而不是short
?
编译器在编译时做出这个决定。它标识提供的参数的类型;然后搜索最佳匹配项。
因此:5的类型是int;因此,编译将对 calculate(int)
的调用放入字节码中。使用强制转换,您基本上指示编译器改为 select calculate(short)
。
需要理解的重要一点是 重载 只是编译时。这在支持 动态调度 的语言中有所不同 - 在这些语言中,"best fitting" 类型在 运行 时确定。正如 Seelenvirtuose 评论的那样:"OO design" 和 多态性 的整个想法是 overriding 是动态的!因此,清楚地区分两者很重要;因为重载是编译时的;最重要的是 运行-time!