下編譯沒有任何問題重寫和返回類型的兼容性
boolean flag = true;
Boolean flagObj = flag;
現在成像以下情形
interface ITest{
Boolean getStatus();
}
class TestImpl implements ITest{
public boolean getStatus(){ // Compile error: return type is incompatible
return true;
}
}
我的問題是關於在提及行的編譯錯誤。我提到的接口返回類型爲Boolean
,但實現的方法返回boolean
(字面)
我的問題是,如果Boolean
和boolean
是兼容的,則編譯器爲什麼抱怨?自動裝箱不適用於此嗎?
嗯,不,它們不是「兼容」的。一個是對象,另一個是原始類型。 Auto {un,}裝箱是一回事,方法原型是另一回事;) – fge
是的,所以答案是語言被定義爲這樣,這不是編譯器中的錯誤。同樣,你不能使用'int'來覆蓋'long'。我的意思是,能夠實現'void'返回方法的'Void'方法會很好,但是你不能。 –