class One {
public One foo() { return this; }
}
class Two extends One {
public One foo() { return this; }
}
class Three extends Two {
public Object foo() { return this; }
}
public Object foo() { 返回这个; }
抛出一个编译错误。这是为什么?有人可以解释为什么“对象”类型是不可能的吗? Object是一二类的基类吗? If So 为什么会抛出错误?
请更改问题的标题,因为我找不到合适的标题。
最佳答案
Three.foo
正在尝试覆盖 Two.foo()
,但它没有正确执行。假设我要写:
One f = new Three();
One other = f.foo();
忽略实际上 Three.foo()
的事实确实返回One
, Three.foo()
的签名不保证。因此,对于 确实 必须返回 One
的方法来说,它不是一个合适的重写.
请注意,您可以更改返回类型并仍然覆盖,但它必须更具体而不是更少。换句话说,这没问题:
class Three extends Two {
public Three foo() { return this; }
}
因为Three
比 One
更具体.
关于Java类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/780954/