如何在Java中從靜態方法呼叫抽象類的非靜態方法?


沒有方法體的方法稱為抽象方法。它只包含方法簽名和分號,以及在其之前的**abstract**關鍵字。

public abstract myMethod();

要使用抽象方法,需要透過擴充套件其類來繼承它,併為其提供實現。

抽象類

包含一個或多個抽象方法的類稱為抽象類。如果它包含至少一個抽象方法,則必須將其宣告為抽象類。

因此,如果要阻止直接例項化類,可以將其宣告為抽象類。

訪問抽象類的非靜態方法

由於不能例項化抽象類,因此也不能訪問其例項方法。只能呼叫抽象類的靜態方法(因為不需要例項)。

示例

abstract class Example{
   static void sample() {
      System.out.println("static method of the abstract class");
   }
   public void demo() {
      System.out.println("Method of the abstract class");
   }
}
public class NonStaticExample{
   public static void main(String args[]) {
      Example.sample();
   }
}

輸出

static method of the abstract class

示例

訪問抽象類非靜態方法的唯一方法是擴充套件它,實現其中的抽象方法(如果有),然後使用子類物件呼叫所需的方法。

abstract class Example{
   public void demo() {
      System.out.println("Method of the abstract class");
   }
}
public class NonStaticExample extends Example{
   public static void main(String args[]) {
      new NonStaticExample().demo();
   }
}

輸出

Method of the abstract class

更新於:2020年7月2日

9K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.