Reputation: 177
If an object is inside of an object how do I manipulate the object it is inside of
Simple example of what I mean written below
How do I be able to make the mouse manipulate the cage variables (decrease cage strength).
public class Cage{
public Cage(){
cageStrength = 1;
Mouse foo = new Mouse ();
foo.eat();
}
public void changeCageStrength(){
cageStrength--;
}
}
}
public class Mouse{
if(condition){
eatPartOfCage();
}
}
public void eatPartOfCage(){
decrease cage strength;
}
Upvotes: 0
Views: 61
Reputation: 201409
You would need to establish a relationship beyond the fact that Mouse foo
is a variable in a constructor of Cage
. For example,
public class Cage {
private Mouse foo;
private int cageStrength;
public Cage() {
cageStrength = 1;
foo = new Mouse(this);
}
public void changeCageStrength() {
cageStrength--;
}
}
And then your Mouse foo
can invoke Cage.changeCageStrength()
in eat()
like
public class Mouse {
private Cage cage;
public Mouse(Cage cage) {
this.cage = cage;
}
public void eat() {
cage.changeCageStrength();
}
}
Upvotes: 3