Override and Revert Compatibility

The following compilation no problem

boolean flag = true; Boolean flagObj = flag; 

Now create the following script

 interface ITest{ Boolean getStatus(); } class TestImpl implements ITest{ public boolean getStatus(){ // Compile error: return type is incompatible return true; } } 

My question is about a compilation error on the specified line. My interface mentions the return type as Boolean , but the implemented method returns a Boolean (literal)

My question is: if Boolean and Boolean compatible, then why does the compiler complain? Is autoboxing applicable here?

+4
source share
3 answers

You can only return a subclass of the parent return type.

Compilation allows you to automatically open and unpack between primitives and wrappers, but this does not make one of the subclasses of the other. Primitives are not classes and cannot be used as you suggest.

I would just get getStatus () return Boolean or return the parent Boolean

In theory, auto-boxing can be expanded to allow what you offer, but I don’t think it is of much use.

In theory, you can also write this

 class A { int method() { ... } } class B extends A { short method() { .... } } 

How the compiler supports implicit boost. However, again, I suspect that this is also of little use.

+5
source

Methods have different signatures on the prototype and implementation. A primitive that is not a class cannot subclass a Boolean prototype. Even with autoboxing, the implementation violates the general prototype. Auto-unboxing is done after the return, so if getStatus was implemented as follows:

 public Boolean getStatus(){ // Compile error: return type is incompatible return Boolean.TRUE; } 

It can be unpacked after return as:

 if(getStatus()) doSomething(); 
0
source

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

0
source

Source: https://habr.com/ru/post/1490479/


All Articles