gpt4 book ai didi

java - 实例化对象时出现错误 "non-static variable this cannot be referenced from a static context"

转载 作者:行者123 更新时间:2023-11-30 03:13:19 25 4
gpt4 key购买 nike

尝试从“Boat”类实例化对象时,出现错误“无法从静态上下文引用非静态变量”。任何帮助将不胜感激!

package simpleboatapp;

/**
*
* @author ragarwala
*/
public class SimpleBoatApp {

public class Boat {

private float speed;
final private float topSpeed = 90;
private boolean sailPosition;

public Boat()
{
speed = 0;
sailPosition = false;
}
public void goFast (String boatName)
{

if (speed < topSpeed)
{
speed = speed + 10;
sailPosition = true;
System.out.println (boatName + "is raising the sail at speed of" + speed + "mph");
}
else
{
sailPosition = true;
System.out.println (boatName + "is raising the sail at maximum speed of" + speed + "mph");
}
}

}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

Boat simpleboat = new Boat(); <--- Error occurs for this line
simpleboat.goFast("Destiny");
}

}

最佳答案

您的Boat类不需要包含类BoatApp中的任何内容。

在这种情况下,您可以使用 static 关键字将其声明为 static 成员类,并且您将能够从静态上下文中实例化它。

public static class Boat {

当你在另一个类中声明一个类时,默认的假设是内部类可以访问外部类中的数据。这意味着它总是需要在作用域内有一个外部类的实例。

如果您想了解更多信息,可以搜索“内部类”。

但在这种情况下,您的 BoatApp 显然不是您想要从成员类 Boat 中访问的东西(它只是 main 的持有者) 方法),因此您只需将 Boat 声明为 static,或者将其移动到自己的文件中。

关于java - 实例化对象时出现错误 "non-static variable this cannot be referenced from a static context",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33194633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com