【问题标题】:Non-static method referenced from a static context [duplicate]从静态上下文引用的非静态方法[重复]
【发布时间】:2015-02-25 18:27:47
【问题描述】:

我有两个相同的错误,它们如下所示:

class FBox {//...}
class FBPlayer
{
    //Initialized instances
    FBox game = new FBox();
    **FBPillar pillar = new FBPillar();**
    **FBObjects objects = new FBObjects();**
    //Lots o Properties...

    public boolean get_Alive() { return this.b_PlayerAlive; }
    public void set_Alive(boolean alive) { this.b_PlayerAlive = alive; }

    //My Error ridden Method
    public void checkCollision()
    {
        if(get_YPos() >= **objects**.get_Ground())
                          ^My Error was incorrect name for my instance
        {
            set_Alive(false);
        }
        else if(get_Bounds().intersects(**pillar**.get_Bounds()))   
                                ^My Error was incorrect name for my instance
        {
            set_Alive(false);
        } 
    }

class FBPillar
{
    public int get_Bounds() {return 'the variable'; }
}

class FBObjects
{
    public int get_Ground() {return 'the variable'; }
}

错误出现在 if 语句和 else if 语句中 当我运行它时,它返回错误:

FBox.java:178: error: non-static method get_Bounds() cannot be referenced from a static context
               else if(get_Bounds().intersects(**FBPillar**.get_Bounds()))

if 语句的错误相同,但使用 FBObjects.get_Ground()) ^

【问题讨论】:

  • 你知道什么是静态方法和非静态方法吗?
  • stackoverflow.com/questions/11993077/… 您正在引用非静态方法,就好像它是静态方法一样。您必须实例化一个对象以访问其上的非静态方法。
  • 将头稍微向右转,然后向下滚动到相关部分。

标签: java static non-static


【解决方案1】:

你在说谁的界限?你可能是说

if (get_Bounds().intersects(pillar.get_Bounds())) {
    …
}

我还要补充一下

 FBPlayer player = new FBPlayer();

表示一个播放器包含一个播放器,这可能不是您想要的。

【讨论】:

  • 感谢 200_success 现在我觉得自己很愚蠢...
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
相关资源
最近更新 更多