我們可以在 Java 中從靜態方法呼叫超類的函式嗎?


繼承可以定義為一個(父/超)類獲取另一個(子/從)類的屬性(方法和欄位)的過程。透過使用繼承,可以按層次結構對資訊進行管理。繼承屬性的類稱為子類,而其屬性被繼承的類稱為超類。簡而言之,在繼承中,可以使用子類的物件訪問超類的成員(變數和方法)。

示例

 線上演示

class SuperClass {
   public void display(){
      System.out.println("Hello this is the method of the superclass");
   }
}
public class SubClass extends SuperClass {
   public void greet(){
      System.out.println("Hello this is the method of the subclass");
   }
   public static void main(String args[]){
      SubClass obj = new SubClass();
      obj.display();
      obj.greet();
   }
}

輸出

Hello this is the method of the superclass
Hello this is the method of the subclass

從靜態上下文中呼叫超類方法

是的,您可以從子類的靜態方法呼叫超類的方法(使用子類的物件或超類的物件)。

示例

 線上演示

class SuperClass{
   public void display() {
      System.out.println("This is a static method of the superclass");
   }
}
public class SubClass extends SuperClass{
   public static void main(String args[]){
      //Calling methods of the superclass
      new SuperClass().display(); //superclass constructor
      new SubClass().display(); //subclass constructor
   }
}

輸出

This is a static method of the superclass
This is a static method of the superclass

更新於: 2020-06-29

3K+ 瀏覽量

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.