在 Java 中,能否從子類呼叫超類的靜態方法?


靜態方法是可以無需例項化類即可呼叫的方法。如果要呼叫超類的靜態方法,可以直接使用類名來呼叫它。

示例

 線上演示

public class Sample{
   public static void display(){
      System.out.println("This is the static method........");
   }
   public static void main(String args[]){
      Sample.display();
   }
}

輸出

This is the static method........

使用例項呼叫靜態方法也能工作,但不推薦這樣做。

 線上演示

public class Sample{
   public static void display(){
      System.out.println("This is the static method........");
   }
   public static void main(String args[]){
      new Sample().display();
   }
}

輸出

This is the static method........

如果在 Eclipse 中編譯上述程式,將會收到以下警告:

警告

The static method display() from the type Sample should be accessed in a static way

呼叫超類的靜態方法

可以呼叫超類的靜態方法:

  • 使用超類的建構函式。
new SuperClass().display();
  • 直接使用超類的名稱。
SuperClass.display();
  • 直接使用子類的名稱。
SubClass.display();

示例

以下 Java 示例以所有三種可能的方式呼叫超類的靜態方法:

 線上演示

class SuperClass{
   public static 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 static method of the superclass
      new SuperClass().display(); //superclass constructor
      SuperClass.display(); //superclass name
      SubClass.display(); //subclass name
   }
}

輸出

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

更新於: 2020年6月29日

3K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告