理解Java按值传递

Pun*_*Raj 0 java pass-by-reference pass-by-value

我经历了stackoverflow中的几个帖子,并搜索其他好的网站,以了解java传递值的概念..

我怀疑如下.

Dog someDog = new Dog("FOO"); //mem location 42
foo(someDog);
someDog.setName("FIFI"); // false

    foo(Dog newDog){
      newDog.name.equals("FOO"); //true
      newDog = new Dog("FIFI");  // create a new DOG object mem location 72. my doubt here
      newDog.name.equals("FIFI"); //true
    }
Run Code Online (Sandbox Code Playgroud)

如上所述,newDog = new Dog("FIFI");我的理解是新的DOG对象在mem位置72处创建并分配给mem位置42处的另一个Dog位置对象.

这是什么意思?在背景..

关心Punith.

das*_*ght 5

一张图片胜过千言万语,所以这是正在发生的事情:

变量到对象图

正如你可以看到,这两个变量someDog在调用者和newDog在foo引用相同的对象开始.在赋值之后,它们引用不同的对象,解释您看到的行为:因为它Dog是通过引用传递的,并且因为您创建了一个新的Dog而不是修改现有的,所以在赋值后newDog变得无关someDog.

请注意,如果你修改现有的狗,图片会有所不同:如果你在newDog.setName("FIFI");里面foo而不是newDog = new Dog("FIFI");,结果会有所不同:图表仍然看起来像中间的图片,但狗的名字本来就是FIFI.