从具有超类的 stati 上下文引用的非静态方法

Non static Method referenced from stati context with superclasses

我创造了一架超级class飞机和一架子class滑翔机

public class Airplanes
{
public String hasWings;
public int numberWheels;
public int numberPassengers;

    public Airplanes(String hasWings, int numberWheels, int numberPassengers)
    {
    // initialise instance variables
    this.hasWings=hasWings;
    this.numberWheels=numberWheels;
    this.numberPassengers=numberPassengers;
    }
}

public class Gliders extends Airplanes
{
private String hasEngine;

public Gliders(String hasWings,int numberWheels,int numberPassengers,String hasEngine)
{
    super(hasWings,numberWheels,numberPassengers);
    this.hasEngine=hasEngine;
}

public void getSpec()
{
    System.out.println("Glider With wings: " + super.hasWings);
    System.out.println("Glider Wheels: " + super.numberWheels);
    System.out.println("Glider Number of passenger: " + super.numberPassengers);
    System.out.println("Glider has engine: " + hasEngine);
}
}

一个新的 class 测试必须初始化 Gliders 并且是这样写的:

public class Test
{
   public Test()
   {
    Airplanes alfa = new Gliders("Yes",2,2,"Np");
    Gliders.getSpec();
   }
}

当我尝试 运行 Gliders.getSpec() 时,它会打印一条错误消息,提示我正在尝试从静态上下文中引用非静态方法。

我只是想知道我尝试做的事情是否合法,如果合法我该如何解决?

你的getSpec方法是非静态方法(实例方法)。所以你需要先创建一个Gliders的实例。

new Gliders().getSpec();

Gliders glider = new Gliders();
glider.getSpec();

如果你还想这样调用getSpec,你需要将getSpec改为静态方法。

public static void getSpec()
{
}