简体   繁体   中英

Referring to a method in another class

I have a class called Hive with some instance variables in it such as 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. 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. 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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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