performmoves()非静态方法错误消息? [重复]

问题描述 投票:1回答:1

我有课:

public class WizardController { [...]

具有私有字段:

private Wizard;

private Wizard;

private int numOfRepeats;

和一个构造函数:

public WizardController(Wizard aWizard1, Wizard aWizard2) {

super();

this.wizard1 = aWizard1;

this.wizard2 = aWizard2;

this.numOfRepeats = 0;

}

并且我创建了两个类对象:

Wizard w1 = new Wizard(OUColour.PINK, 1);

Wizard w2 = new Wizard(OUColour.PINK, 2);

加上类方法:

public void performMoves() {

promptForNumOfRepeats();

flyWizards();

WizardController.switchTrack(w1, w2);

slitherWizards();

WizardController.switchTrack(w1, w2);

flyWizards();

}

问题!

我已经像这样从主类中调用了该方法:

WizardController.performMoves();

为什么会收到此错误消息?

错误:第1行-无法从静态上下文引用非静态方法performMoves()

java compiler-errors static non-static
1个回答
0
投票

我认为这可能是您想要的:

class Wizard {
  // attributes
}

class WizardController {
  private Wizard wizard;

  public Wizard getWizard() {
    return wizard;
  }

  public void setWizard(Wizard wizard) {
    this.wizard = wizard;
  }

  public void performMoves() {
    // do nothing
  }
}

public class Demo {
  public static void main(String[] args) {

    // You cannot do this: WizardController.performMoves(),
    // since performMoves is not a static method

    // Call performMoves the right way
    Wizard wizard = new Wizard();
    WizardController controller = new WizardController();
    controller.setWizard(wizard);
    controller.performMoves();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.