Reputation: 381
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;
}
}
}
Upvotes: 0
Views: 103
Reputation: 115
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;
}
}
}
Upvotes: 2
Reputation: 713
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;
}
}
}
Upvotes: 2
Reputation: 285460
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.
Upvotes: 1