passing by reference in Java doubts

后端 未结 5 1788
借酒劲吻你
借酒劲吻你 2021-01-26 05:07

So I was reading this post and response no. 2. In that example, after calling that method, does the Dog value at address 42, name\'s changes to Max?

Dog myDog;

         


        
5条回答
  •  感情败类
    2021-01-26 05:28

    myDog and someDog share the same object and contain the same address value at the beginning. That is, both variables tell the JVM how to get to the Object Dog in memory (heap). So if you change something by invoking the setName method on someDog, myDog 'will feel' the effects!

    After someDog = new Dog("Fifi") a new Object Dog is created (Fifi) and the someDog variable contains a new value/address for Fifi. That is, the value of someDog changes and will tell the JVM how to get to Fifi from now on. At this point, every change on someDog won't affect myDog anymore.

    Check my answer (the one with the picture) on that post and note that I didn't use the word "pointer" and not even the word "reference" this time! ;)

提交回复
热议问题