"Non-static method cannot be referenced from a static context" 但没有静态变量或方法

"Non-static method cannot be referenced from a static context" but no static variable or method

我必须做一个作业(在 Java 中,使用 BlueJ)并且在这个作业的一部分中,我需要在 PlayerShip class 中有一个 'Move' 方法。根据作业说明,我也需要在Gun class中有这个相同的方法,并且PlayerShip class中的方法必须调用Gun class中的方法两次。作为参考,我提供了我的 Gun class:

的代码
    public class Gun
{
    private int position;
    private int power;
    private int points;
    private boolean justFired;

    public Gun(int initialPosition, int initialPower) 
    {
        position = initialPosition;
        power = initialPower;
    }

    public void Move(int distance)
    {
        position = position + distance;
    }
}

这是我的 PlayerShip class:

的代码
public class PlayerShip
{
    private int position;

    public PlayerShip()
    {
        position = Global.promptInt("Player position: ");
        Gun gun1 = new Gun(position - 1, 5);
        Gun gun2 = new Gun(position + 1, 5);
    }

    public void Move(int distance)
    {
        position = position + distance;

        Gun.Move(distance);

    }
}

现在的问题是,我一直收到错误消息:

non-static method Move(Int) cannot be reference from a static context

当我尝试从 PlayerShip class 中的 Move() 方法调用 Gun class 中的 Move() 方法时。我不知道为什么会收到此错误,因为 none 的变量或方法是静态的,而且我没有想法,因此感谢您的帮助

编辑:标记软件非常死板,如果变量是静态的,则不接受我的代码

Gun.Move(distance); 

是您调用静态方法的方式,而 Move() 不是。

您希望 Gun 的实例调用 Move() 方法。

例如

Gun gun = new Gun();
gun.Move()

在您的 Move 方法中调用 Gun.Move。

枪是 class 而不是物体。因此,您尝试在 Gun 的 'blueprint' 上调用 Move,而不是在实际的 Gun 对象上调用。

当您实例化您的 PlayerShip class 时,您创建了两个 Gun 实例。如果我假设您想要 PlayerShip class 到 'have' 两把枪是对的。您可以为 PlayerShip class 提供两个私有枪支变量,以便 move 方法可以访问它们。

public class PlayerShip
{
private int position;
private Gun gun1;
private Gun gun2;

// rest of code 

}

然后您可以从这里访问您的 PlayerShip 对象拥有的枪支对象。

这样创建构造函数和移动方法:

public PlayerShip()
{
    position = Global.promptInt("Player position: ");
    gun1 = new Gun(position - 1, 5);
    gun2 = new Gun(position + 1, 5);
}

public void Move(int distance)
{
    position = position + distance;

    gun1.Move(distance);
    gun1.Move(distance);

}

您在尝试调用 Gun class 上的方法而不是单个实例时收到静态引用错误。

static 关键字意味着它对于对象的每个实例都是相同的。

希望这对您有所帮助,一开始很难理解对象的工作原理。

继续练习!