English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

如何从Java中的静态方法调用抽象类的非静态方法?

没有主体的方法称为抽象方法。它仅包含带有半冒号和前面的抽象关键字的方法签名。

public abstract myMethod();

要使用抽象方法,您需要通过扩展其类并为其提供实现来继承它。

抽象类

包含0个或多个抽象方法的类称为抽象类。如果它至少包含一个抽象方法,则必须将其声明为abstract。

因此,如果要直接阻止类的实例化,可以抽象地声明它。

访问抽象类的非静态方法

由于无法实例化抽象类,因此也无法访问其实例方法。您只能调用抽象类的静态方法(因为不需要实例)。

示例

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
猜你喜欢