如果我将 byte
更改为 int
,我会收到编译器错误。你能解释一下这个问题吗?
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
}
最佳答案
If i change the
byte
toint
I get a compiler error.
如果你这样做,你会得到这个:
public class A {
protected int xy(int x) { return 0; }
}
class B extends A {
protected long xy(int x) { return 0; }
}
...xy
方法的唯一区别是它们的返回类型。方法不能仅仅通过它们的返回类型来区分,这就是 Java 的定义方式。考虑一下:
myInstance.xy(1);
应该调用哪个xy
? long xy(int x)
还是 int xy(int x)
?
如果您的目标是覆盖B
中的xy
,那么您需要将其返回类型设置为int
为了匹配A#xy
。
关于java - 当我尝试使用具有相同名称和参数类型的两个方法时,为什么会出现编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22838019/