java - 方法重载在这里如何工作?
问题描述
我有两个分别带有参数 int 和 Integer 的重载方法。当我通过传递5调用打印方法时,为什么它调用第一个打印方法。它如何识别调用哪个方法?
public class Main {
public static void main(String[] args) {
print(5);
}
static void print(int a) {
System.out.println("Calling first print");
}
static void print(Integer a) {
System.out.println("Calling second print");
}
}
解决方案
public class Test
{
static void print( int a )
{
System.out.println( "Calling first print" );
}
static void print( Integer a )
{
System.out.println( "Calling second print" );
}
public static void main( String[] args )
{
print( 5 );
print( new Integer(5) );
}
}
print( 5 );
将输出 Calling first print ,因为您正在传递 5 ,这是一个 premitive 。print( new Integer(5) );
将输出 Calling second print 因为您将 5 作为整数对象传递,因此方法static void print( Integer a )
具有更高的优先级。
推荐阅读
- html - 子 div 是可滚动的,但在子元素中添加内容时,主体的高度仍然会增加
- c# - 仅显示一次 Gameobject 统一
- android - Android:滚动时不调用 OnbindViewHolder
- reactjs - 为什么 react-native start 命令停留在“加载依赖关系图,完成”上。
- html - CSS - 添加文本时导航栏变得不模糊
- wcf - 从 Android 使用 WCF
- javascript - react-redux Reducer 不会将对象传递给商店
- scala - 在 spark scala 函数中将 List 作为参数传递会出错
- python - 在 Tkinter 中绑定 '<' 键
- amazon-s3 - 如何检查 awscli 和兼容的 botocore 包是否已安装