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);
}
}