当我尝试使用具有相同名称和参数类型的两个方法时,为什么会出现编译错误?

aze*_*eem 5 java

如果我更改byteint我得到编译器错误.你能解释一下这个问题吗?

public class A {
   protected int xy(int x) { return 0; }
}

class B extends A {
   protected long xy(int x) { return 0; } //this gives compilor error
   //protected long xy(byte x) { return 0; } // this works fine
}   
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

如果我更改byteint我得到编译器错误.

如果你这样做,你有这个:

public class A {
   protected int xy(int x) { return 0; }
}

class B extends A {
   protected long xy(int x) { return 0; }
}   
Run Code Online (Sandbox Code Playgroud)

......而且方法的唯一区别xy是它们的返回类型.方法不能仅通过它们的返回类型来区分,这就是Java的定义方式.考虑一下:

myInstance.xy(1);
Run Code Online (Sandbox Code Playgroud)

xy应该打电话给哪个人?long xy(int x)还是int xy(int x)

如果你的目标是覆盖 xy in B,那么你需要设置它的返回类型int才能匹配A#xy.