如何在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.