java方法重载
1什么是方法重载
当你在一个类中看到同名的但是参数个数或者类型不同的方法时,就发生了方法重载
2,分类
①通过改变参数的数目
class Math{
int sum (int x,int y){
return x + y;
}
int sum(int x,int y,int z){
return x + y + z;
}
}
public class ex {
public static void main(String[] args) {
Math c = new Math();
System.out.println(c.sum(1,2));
System.out.println(c.sum(1,2, 3));class Math{
int sum (int x,int y){
return x + y;
}
int sum(int x,int y,int z){
return x + y + z;
}
}
public class ex {
public static void main(String[] args) {
Math c = new Math();
System.out.println(c.sum(1,2));
System.out.println(c.sum(1,2, 3));
}
}
}
}
结果
3
6
Process finished with exit code 0
②通过改变参数的类型
class Math{
int sum (int x,int y){
return x + y;
}
double sum(int x,double y){
return x + y ;
}
}
public class ex {
public static void main(String[] args) {
Math c = new Math();
System.out.println(c.sum(1,2));
System.out.println(c.sum(1,2.2));
}
}
结果
3
3.2
Process finished with exit code 0
3,不能只通过更改返回值的类型来进行重载,会存在歧义,
先看一下下面的代码
class Math{
int sum (int x,int y){
return x + y;
}
doulbe sum(int x,int y){
return x + y ;
}
}
public class ex {
public static void main(String[] args) {
Math c = new Math();
System.out.println(c.sum(1,2));
}
}
当c 去调用sum方法时,编译器根本分不清你到底想用哪个一方法,接收的参数类型和数目都是一样的,又因为编译错误要比运行时错误好的多。所以java中不允许仅仅通过改变返回值类型来重载。