這是一個新手問題。 我讀過JVM的執行從搜索層次結構中最低類的methodname開始,如果該方法在該類中不可用,它將遍歷父類來尋找方法。JVM - 子類方法的執行順序和@override的使用
如果是這種情況,那麼爲什麼我們需要使用「@override」將自定義邏輯添加到繼承類?
下面的例子說明了我的問題
class superclassA
{
method()
{
}
}
class subclassB extends superclassA
{
@Override
//While executing if JVM starts looking for the method name from the lowest hierarchy
//then why do we have to use "override" as the methodname will be matched from the lowest level itself?
method()
{
--custom subclass specific code...
}
}
你不需要'@ Override'。它僅在最近才引入(Java 1.5),並且完全是可選的。 - 它的目的是避免程序中的錯誤,因爲它告訴編譯器你實際上*打算*覆蓋特定的方法。例如,如果您錯誤地輸入了方法的名稱,那麼繼承的方法會被* not *覆蓋,並且可能會導致一些令人討厭的錯誤。使用'@ Override'時,編譯器至少會警告你,如果註釋的方法不*實際覆蓋繼承的方法。 – JimmyB
謝謝hanno..it解釋 – UnderDog
@HannoBinder 1。5是相當新近的?在1.5版發佈之前,它已經超過1.0了。 –