Immutable and pass by value

前端 未结 4 1956
我在风中等你
我在风中等你 2020-12-29 14:01

I have the following code which has
a mutable Person class, String and a method to modify the instances of String and Person

    class Person{

int a = 8         


        
4条回答
  •  春和景丽
    2020-12-29 14:39

    In modifyObject, When you assign to str, you're not mutating str, you're setting it so that it points to a different object. Since it's passed by value, the str pointer local to your modifyObject method is a copy of the s pointer in main, so when you change the former, it does not affect le later.

    On the other hand, when it comes to p, the one in modifyObject is still a copy of the one in main, but both pointers refer to the very same object in memory, hence if you call a method on it from modifyObject, you're actually mutating the thing pointed to by p.

提交回复
热议问题