Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...