解释评论中提到的问题

Explain the questions mentioned in the comments

        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?
        }
    }

请解释评论中提到的问题 代码的输出是 f.myBar.barNum 是 28 myBar.barNum in change是99 myBar.barNum在变化现在是420

f.myBar.barNum after changeIt is 99

Java 在方法中传递对对象的引用。如果你愿意,你可以称它为指针。假设您在 class foo 中有对象 myBar 并将其传递给 change it 方法。它不传递对象本身,而是传递对该对象的引用(如果您愿意,可以是指针)。

当你做 myBar.barNum = 99;这里 myBar 指向 class foo 中的实际对象 myBar 并更改其 属性。

当你做 myBar = new Bar();这里的 myBar(正如我们所见,它是指向一个对象的指针)开始指向一个不同于 class foo 的 myBar 的新 Bar 对象。您将其更改为 400,并且在该对象所在的上下文(方法)中它是 400。当您离开方法时,您 return 到原始对象所在的 class foo。由指向 99 的指针更改。

希望我解释得当。如果所有的东西都不叫 mybar 会更容易理解。因为在 myBar=new Bar() 行中,您实际上使用的是本地 mybar(在方法中)而不是全局 mybar。例如:

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
    }