Mutable or immutable class?

后端 未结 8 1880
死守一世寂寞
死守一世寂寞 2020-12-17 21:44

I had read in some design book that immutable class improves scalability and its good practice to write immutable class wherever possible. But I think so immutable class inc

8条回答
  •  不思量自难忘°
    2020-12-17 22:03

    I think, if you want to share the same object among different variables, it needs to be immutable.

    For instance:

    String A = "abc";
    String B = "abc";
    

    String object in Java is immutable. Now both A & B point to the same "abc" string. Now

    A = A + "123";
    System.out.println(B);
    

    it should output:

    abc
    

    Because String is immutable, A will simply point to new "abc123" string object instead of modifying the previous string object.

提交回复
热议问题