0

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; } 
1
  • 2
    To clear up a misconception: an object is never "inside" another object. Rather, an object can hold a reference to another object, which analogous to a person knowing somebody else's phone number. Commented Nov 17, 2019 at 1:57

1 Answer 1

3

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(); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Noting that irl it’s not up to the mouse to determine if it can alter the cage strength, rather a combination of the mouse and the cage (could be a brick cage, could be a mutant mouse with toll steel teeth).
@DaveNewton It could always be "Slippery Jim" diGriz.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.