建構函式可以在 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 年 7 月 30 日

14 千次瀏覽

啟動你的 職業

完成課程,獲得認證

開始學習
廣告