0

I am trying to write a method where a reference to an object will refer to another object.

Here I created two "Box" objects, now if I want box and box2 both to refer to box2, I could have written box=box2, but I want to do the same thing via a method which I wrote as "public void change(Box b) {}", but it isn't working.

As far I know Java passes argument to parameters as "call by reference". But when I write "box2.change(box);" the "box" object still refers to original "box" instead of "box2"

public class Main {
    public static void main(String[] args) {
        Box box = new Box(50, 50);
        box.show();

        Box box2 = new Box(100, 100);
        box2.show();

        box2.change(box);
        // After applying method
        box.show();
    }
}


class Box {
    int height;
    int width;

    Box(int h, int w) {
        this.height = h;
        this.width = w;
    }

    public void change(Box b) {
        b = this;
    }

    public void show() {
        System.out.println("H: " + this.height + " " + "W: " + this.width);
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
raiyan106
  • 123
  • 2
  • 9
  • `b=this;` will not work, what you want to do instead is set: `b.height = this.height;` and `b.width = this.width;` – Nir Alfasi Nov 18 '17 at 17:18
  • `b = this;` does nothing to the original **variable** – Hovercraft Full Of Eels Nov 18 '17 at 17:21
  • It doesn't work because the `b` you get in the `change` method is **not** **the reference** (or pointer) to that object which you use outside of it. Instead you get a copy reference which points to the same object. If you now redirect this copy reference, it won't affect other references which are used outside the method. So `b` inside the method and `box` from `box2.change(box);` both point to the same object but they are different pointers (per identity). It's like if you would do `Box second = first;`. If you later redirect `second = third` it won't affect `first`. – Zabuzard Nov 18 '17 at 17:22
  • @Zabuza so if it creates a copy reference instead of referring the original object, then how am I supposed to perform the action I want to (which is pass the reference) via this method? – raiyan106 Nov 18 '17 at 17:24
  • Well, you can't. – Zabuzard Nov 18 '17 at 17:25
  • However you could use what is called **Proxy-pattern** to realize such a behavior. There you would have a wrapping class, the proxy. Which forwards all calls to its true object (stored internally). And then you can just exchange the internal reference. So for example a `BoxProxy` which internally holds a `Box` object. It offers the same methods than `Box` by just forwarding all calls to its internal `Box`. You can then exchange the internal `Box` object. – Zabuzard Nov 18 '17 at 17:28

0 Answers0