Overriding and return type compatibility

半世苍凉 提交于 2019-11-29 14:43:17

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.

As we know, we can only return a sub-class of the parent's return type.Here Boolean is wrapper class while boolean is primitive data type.In short both are different as wrapper class and primitives.So it gives error of incompatible.

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!