class Bar{
int barNum=28;
}
class Foo{
Bar myBar = new Bar();
void changeIt(Bar myBar){ //Here is object's reference is passed or the object is passed?
myBar.barNum = 99;
System.out.println("myBar.barNum in changeIt is " + myBar.barNum);
myBar = new Bar(); //Is the old myBar object destroyed now and new myBar is referring to something new now?
myBar.barNum = 420;
System.out.println("myBar.barNum in changeIt is now "+myBar.barNum);
}
public static void main(String args[]){
Foo f = new Foo();
System.out.println("f.myBar.barNum is "+f.myBar.barNum); //Explain f.myBar.barNum!
f.changeIt(f.myBar); //f.myBar refers to the object right? but we need to pass reference of the type Bar in changeIt!?
System.out.println("f.myBar.barNum after changeIt is "+ f.myBar.barNum); //How do you decide f will call which myBar.barNum?
}
}
Explain the questions mentioned in the comments please The output of the code is f.myBar.barNum is 28 myBar.barNum in changeIt is 99 myBar.barNum in changeIt is now 420
f.myBar.barNum after changeIt is 99
Java passes a reference to an object in a method. You can call it a pointer if you want. Let's say you have the object myBar in the class foo and you pass it to the change it method. It doesn't pass the object itself it passes a reference to that object (a pointer if you prefer).
When you do myBar.barNum = 99; here myBar points to the actual object myBar in the class foo and changes its property.
When you do myBar = new Bar(); the myBar here (which as we saw is pointer to an object) starts to point to a new Bar object different from the myBar of the class foo. You change it to 400 and in the context where that object lives (the method) it is 400. When you leave the method you return to the class foo where is the original object. Changed by its pointer to 99.
I hope I explained it properly. If everything is not called mybar it would be easier to understand. Because in the line myBar=new Bar() you are actually using the local mybar (in the method) and not the global one. For example:
Bar myBar = new Bar();
void changeIt(Bar aBar){
aBar.barNum = 99; //Here aBar is a pointer to the myBar above and changes it
aBar = new Bar(); //Here aBar points to a new myBar instance
a.barNum = 420; //This will be lost when you leave the method with the new instance created
}