The following compiles without any problem
boolean flag = true;
Boolean flagObj = flag;
Now imaging the following scenario
interface ITest{
Boolean getStatus();
}
class TestImpl implements ITest{
public boolean getStatus(){ // Compile error: return type is incompatible
return true;
}
}
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.
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.
In theory you could also write this
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.
The methods have different signatures on the prototype and the implementation. The primitive, not being a class, cannot subclass the Boolean
of the prototype. Even with autoboxing, the implementation violates the general prototype. Auto-unboxing is performed after a return so if getStatus was implemented like so:
public Boolean getStatus(){ // Compile error: return type is incompatible
return Boolean.TRUE;
}
it could be unboxed after returning as:
if(getStatus()) doSomething();
我们知道,我们只能返回父类返回类型的子类.Here Boolean是包装类,而boolean是原始数据类型。简而言之,两者作为包装类和原语不同。因此它给出了不兼容的错误。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.