Immutable class?

2019-01-02 20:20发布

How can one make a Java class immutable, what is the need of immutability and is there any advantage to using this?

8条回答
梦寄多情
2楼-- · 2019-01-02 20:47

Immutability can be achieved mainly in two ways:

  • using final instance attributes to avoid reassignment
  • using a class interface that simply doesn't allow any operation that is able to modify what is inside your class (just getters and no setters

Advantages of immutability are the assumptions that you can make on these object:

  • you gain the no-side effect rule (that is really popular on functional programming languages) and allows you to use objects in a concurrent environment easier, since you know that they can't be changed in a atomic or non atomic way when they are used by many threads
  • implementations of languages can treat these objects in a different way, placing them in zones of memory that are used for static data, enabling faster and safer use of these objects (this is what happens inside the JVM for strings)
查看更多
唯独是你
3楼-- · 2019-01-02 20:51

Immutable class are those whose objects cannot be changed after creation.

Immutable classes is useful for

  • Caching purpose
  • Concurrent environment (ThreadSafe)
  • Hard for inheritance
  • Value cannot be changed in any environment

Example

String Class

Code Example

public final class Student {
    private final String name;
    private final String rollNumber;

    public Student(String name, String rollNumber) {
        this.name = name;
        this.rollNumber = rollNumber;
    }

    public String getName() {
        return this.name;
    }

    public String getRollNumber() {
        return this.rollNumber;
    }
}
查看更多
登录 后发表回答