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岁 changeIt中的myBar.barNum为99 changeIt中的myBar.barNum现在为420
f.myBar.barNum after changeIt is 99
答案 0 :(得分:0)
Java传递对方法中对象的引用。如果需要,可以将其称为指针。假设你在类foo中有对象myBar,并将它传递给change it方法。它不传递对象本身它传递对该对象的引用(如果您愿意,则为指针)。
当你做myBar.barNum = 99;这里myBar指向类foo中的实际对象myBar并更改其属性。
当你做myBar = new Bar();这里的myBar(我们看到的是指向对象的指针)开始指向一个不同于类foo的myBar的新Bar对象。您将其更改为400,并且在该对象所在的上下文中(方法)它为400.当您离开该方法时,您将返回到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
}