Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

java - Overriding and return type compatibility

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...