Overriding and return type compatibility

孤者浪人 提交于 2019-12-18 08:56:13

问题


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 ?


回答1:


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.




回答2:


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.




回答3:


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();


来源:https://stackoverflow.com/questions/17548406/overriding-and-return-type-compatibility

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