【问题标题】:Referring to a method in another class引用另一个类中的方法
【发布时间】:2013-12-06 01:40:24
【问题描述】:

我有一个名为 Hive 的类,其中包含一些实例变量,例如 Honey。我有另一个名为 Queen 的类,我想使用一个名为 takeHoney() 的方法,我的蜂巢类中有该方法可以移除 2 个单位的蜂蜜(如果可用)。我试图做的是向 Queen 类添加一个构造函数,该类将 Hive 作为参数并将其存储在本地,以便我可以从 Queen 访问 Hive 中的方法,但它不起作用。有什么问题?

public class Queen extends Bee{

    int type = 1;

    public Queen(Hive hive){

    }

    public Queen(int type, int age, int health){
        super(type, age, health);
    }

    public Bee anotherDay(){
        return this;
    }

    public boolean eat(){
        if(Hive.honey > 2){
            hive.takeHoney(2);
            return true;
        }else{
            return false;
        }   
    }
} 

【问题讨论】:

  • “它不工作”...请更具体。您似乎面临的具体问题是什么?
  • 您没有将配置单元存储在实例变量中。该构造函数将hive 作为参数,但不执行任何操作。
  • 您应该始终复制/粘贴您收到的确切错误消息。

标签: java methods constructor


【解决方案1】:

你必须创建一个 Hive 实例才能从 Hive 调用方法

public class Queen extends Bee{

    int type = 1;
-->    Hive hive = null;
    public Queen(Hive h){
   -->         hive = h;
        }

    public Queen(int type, int age, int health){
        super(type, age, health);
    }

    public Bee anotherDay(){
        return this;
    }

        public boolean eat(){
   -->         if(hive.honey > 2){
                hive.takeHoney(2); 
                return true;
            }else{
                return false;
            }   
        }
} 

【讨论】:

  • 实际上,如果方法是静态的,则无需创建实例。你甚至可以做Hive hive; hive.takeHoney(2);,它会起作用的。但是 OP 显然不明白静态变量和实例变量/方法之间的区别。
  • 谢谢你——这很好用。只是提醒其他可能看到这个问题而不是“hive = hive;”的人正如你所说,我必须输入“this.hive = hive;”用于编译代码。再次感谢
  • 是的,抱歉我没有测试它。它应该是“this.hive”.. 我更新了代码,但我只是将构造函数的参数更改为 h
【解决方案2】:

您指的是静态的 Hive。您需要实例化它,然后调用该对象的方法。

public class Queen extends Bee{

int type = 1;
Hive h;
public Queen(Hive hive){

    h = hive;


}

public Queen(int type, int age, int health){
    super(type, age, health);
}

public Bee anotherDay(){
    return this;
}

public boolean eat(){
    if(h.honey > 2){
        h.takeHoney(2);
        return true;
    }else{
        return false;
    }   
}

}

【讨论】:

  • 如果 Hive 中的所有内容都是静态的,则无需创建 Hive。
【解决方案3】:

这绝对没有任何作用:

public Queen(Hive hive){

}

你在哪里将它分配给类中的一个字段?回答你不知道。

解决方案:你应该这样做!

public Queen(Hive hive){
  this.hive = hive;
}

当然还要给女王一个叫做蜂巢的领域。然后就可以使用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2011-06-17
    相关资源
    最近更新 更多