在执行基本方法重载程序时,我始终收到以下错误:
sh-4.3 $ javac HelloWorld . Java < br > HelloWorld . Java:10:错误:方法show()已在类hello world中定义< br > static void show()< br > hello world . Java:25:错误:方法show(int,int)已在类hello world中定义< br> static void show(int a,int b)
2错误
该程序的代码如下:
public class HelloWorld{
static int show()
{
int c = 5+10;
System.out.println("hello");
return c;
}
static void show()
{
int c = 5+10;
System.out.println("void"+c);
}
static int show(int a,int b)
{
int c = a+b;
System.out.println("hello");
return c;
}
static void show(int a,int b)
{
int c = a+b;
System.out.println("hello void args"+c);
}
public static void main(String []args){
int a=5,b=5;
int c=show();
System.out.println("hello"+c);
show();
c= show(a,b);
System.out.println("hello"+c);
show(a,b);
}
}
不能在java中定义两个名称相同、参数相同但返回类型不同的方法。
在oracle教程中,您可以找到答案:
编译器在区分方法时不考虑返回类型,因此即使两个方法的返回类型不同,也不能用相同的签名声明它们。
java中方法的签名有一个非常简单的规则:
方法签名仅包括方法输入参数的名称。
因此方法的返回类型不包含在方法签名中。
另一方面,过载意味着:
在一个类中有两个或多个方法,具有完全相同的名称但参数类型不同或参数数量不同,或两者都有。
编译器不会指出方法的返回类型,所以无法理解带有两个int参数的两个show方法之间的区别。没有参数的两个show方法也会发生同样的错误。
希望澄清会有所启发。
祝你好运
静态空显示(int a,int b)
静态空显示(int a,int b)
这在java中不受支持。因为两种方法的参数列表是相同的
有两种方法可以在java中重载该方法
By changing number of arguments
By changing the data type