java: advantages of immutable objects in examples

2020-03-04 08:33发布

give me please examples where I could see advantages of immutable objects. Info I found in internet are concentrated in threads. I don't know about threads yet. would be great if the examples would use simple principles

8条回答
Anthone
2楼-- · 2020-03-04 09:06

A good example is the String class:

A good summary of reasons for immutable objects can be found here

查看更多
手持菜刀,她持情操
3楼-- · 2020-03-04 09:23

As Java returns by value (i.e. object references are returned from methods), if for example I return a String like so:

private String myString = "foo";

public String getString() {
    return this.myString;
}

and the String class wasn't immutable, then the caller of getString() could modify myString, which may not be the desired behaviour; other parts of the system might not want or expect myString to change. So the caller can only change the object which myString points to, not myString itself.

查看更多
登录 后发表回答