Java 中建構函式可以被重寫嗎?


如果父類和子類有相同的方法,包括名稱、返回型別和引數,並且如果嘗試使用子類的物件呼叫它

那麼將呼叫子類中的方法。

建構函式看起來像方法,但它不是方法。它沒有返回型別,並且其名稱與類名稱相同。

但是,建構函式不能被重寫。如果你嘗試在子類中編寫父類的建構函式,編譯器會將其視為方法,並期望返回型別並生成編譯時錯誤。

示例

class DemoTest{
   DemoTest(){
      System.out.println("This is the constructor of the demo class");
   }
}
public class OverridingConstructor extends DemoTest {
   DemoTest(){
      System.out.println("This is the constructor of the demo class");
   }
}

輸出

C:\Sample>javac Example.java
Example.java:2: error: class Sample is public, should be declared in a file named Sample.java
public class Sample {
^
1 error

更新時間: 2019-07-30

14,000+ 次瀏覽

Kickstart Your Career

完成課程後獲得認證

立即開始
廣告
© . All rights reserved.