Alex Rivera | Logout

java: advantages of immutable objects in examples

Asked 2011-04-13T16:41:19.963
9

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

Edit
Report

1 Answer

1

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.

answered 2011-04-13T16:51:00.153

Your Answer