[Solved] Explain the questions mentioned in the comments [duplicate]


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
    }

solved Explain the questions mentioned in the comments [duplicate]