覆盖和返回类型兼容性 [英] Overriding and return type compatibility
问题描述
以下编译没有任何问题
boolean flag = true;
Boolean flagObj = flag;
现在成像以下场景
interface ITest{
Boolean getStatus();
}
class TestImpl implements ITest{
public boolean getStatus(){ // Compile error: return type is incompatible
return true;
}
}
我的问题是关于上述行的编译错误。 My Interface提到返回类型为 Boolean
但实现的方法返回 boolean
(文字)
My question is about the compile error at the mentioned line. My Interface mentions return type as Boolean
but the implemented method returns boolean
(the literal)
我的问题是,如果布尔
和布尔
是兼容然后编译器为什么抱怨?自动装箱不适用于此吗?
My question is, if Boolean
and boolean
are compatible then why the compiler is complaining ? Doesn't the autoboxing apply here ?
推荐答案
您只能返回父级返回类型的子类。
You can only return a sub-class of the parent's return type.
编译允许您在原语和包装器之间自动装箱和取消装箱,但这不会使另一个成为另一个子类。基元不是类,不能按照你建议的方式使用。
The compile lets you auto-box and unbox between primitives and wrappers but this doesn't make one a sub-class of the other. Primitives are not classes and cannot be used in the way you suggest.
我只需要getStatus()返回布尔
或让父母返回布尔
I would just have the getStatus() return Boolean
or make the parent return boolean
理论上,自动装箱可以扩展到允许你的建议,但我觉得它没什么用处。
In theory, auto-boxing could be extended to allow what you suggest, but I don't imagine much use for it.
理论上你也可以写这个
class A {
int method() { ... }
}
class B extends A {
short method() { .... }
}
由于编译器支持隐式向上转换。不过,我怀疑这个用途也没什么用。
As the compiler supports implicit upcasting. However again, I suspect there is not much use for this either.
这篇关于覆盖和返回类型兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!