在同一个类中,定义多个同名的方法,每个方法有不同的参数类型或参数个数,称为方法重载
1.同一个类,方法名相同,参数不同
2.参数:个数、类型、类型顺序
3.是否重载与返回值无关
例如:方法名为 fn
fn(6);//调用1
fn(6.1);//调用2
fn(6,8);//调用3
fn(6,8.1);//调用4
fn(8.1,6);//调用5
1 public static int fn(int a)
{
return 1;
}
2 public static int fn(double a)
{
return 1;
}
3 public static int fn(int a,int b)
{
return 1;
}
4 public static int fn(int a,double b)
{
return 1;
}
5 public static int fn(double a,int b)
{
return 1;
}
方法重载与隐式类型转换
1.传入的参数,如果无法找到完全匹配的重载方法,则会尝试进行隐式类型转换。
2.两个重载方法都可以进行隐式转换,优先选择取值范围更接近的。
例如:
int可以隐式转换成double(8个字节)
int可以隐式转换成float(4个字节)
所以同时有double和float类型存在时,优先选取float