简体   繁体   English

引用另一类中的方法

[英]Referring to a method in another class

I have a class called Hive with some instance variables in it such as Honey. 我有一个名为Hive的类,其中包含一些实例变量,例如Honey。 I have another class called Queen which I want to use a method called takeHoney() which I have in my hive class to remove 2 units of honey if it is available. 我有另一个名为Queen的类,我想使用一个名为takeHoney()的方法,在我的蜂巢类中,该方法可以除去2个蜂蜜(如果有)。 What I have attempted to do is add a constructor to the Queen class that takes a Hive as a parameter and stores it locally so I can access the methods in Hive from Queen but it isn't working. 我试图做的是在Queen类中添加一个构造函数,该构造函数将Hive作为参数并将其存储在本地,这样我就可以从Queen访问Hive中的方法,但是它不起作用。 What is the problem? 问题是什么?

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;
        }   
    }
} 

you have to to create an instance of Hive to call methods from Hive 您必须创建一个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;
            }   
        }
} 

You're referring to Hive statically. 您是静态地引用Hive。 You need to instantiate it and then call the methods on that object. 您需要实例化它,然后在该对象上调用方法。

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;
    }   
}

} }

This does absolultely nothing: 这绝对不会做任何事情:

public Queen(Hive hive){

}

Where do you assign it to a field in the class? 您在哪里将其分配给班级中的某个字段? Answer you don't. 回答你不。

Solution: you should! 解决方案:应该!

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

And also of course give Queen a field called hive. 当然也要给女王一个叫做蜂巢的领域。 Then you will be able to use it. 这样您就可以使用它了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM