0

I have two classes: Grid and Robot. And I call:

Grid g = new Grid(5,5);
Robot a = new Robot(1, 1, g);
Robot b = new Robot(2, 2, g);

Would it would be possible for me to share g between the two robot classes so that modifying g using a method called on Robot a, would it also modify Robot b in the same way?
Or is there another way to do this?

Michał Szewczyk
  • 7,540
  • 8
  • 35
  • 47
okbuthow
  • 59
  • 9
  • This is fine, however you would need to be careful that access to `g` is synchronized. To have a method on `g` affect either `Robot` you will need to let `g` know about the robots. You might want to consider doing something more like: `Grid g = ..; Robot a = new Robot(1, 1); g.addRobot(a); ...` (unless the `Robot` constructor calls some method on `g` to let it know the robot exists) – Tibrogargan Oct 15 '16 at 05:21
  • Robot a and b got two different references of object g but that two reference point the same g object. But as @Tibrogargan says you should careful to access to object g in multi threading environment. – seal Oct 15 '16 at 05:26
  • 1
    @seal Java is pass-by-value, so they get the same reference (the *value* of the reference is being passed, not a reference to the `Grid` object) – Tibrogargan Oct 15 '16 at 05:28
  • I got it, thank you all – okbuthow Oct 15 '16 at 05:59

1 Answers1

1

Since Java is pass by value, when you are passing reference as an argument to the method, you are passing it's value which is the memory address and as consequence you receive the reference to the object in that method.
So your code works as you are expecting.
You can check it by modifying Grid g value in some of robots and check in other robot if it has changed.
For more about pass-by-value you can read here.

Hope it helps.

Community
  • 1
  • 1
Michał Szewczyk
  • 7,540
  • 8
  • 35
  • 47