How can we make any class immutable in Java?

Answered

How can we make any class immutable in Java?

Ninja Asked on 18th September 2018 in Java.
Add Comment
1 Answer(s)
Best answer

To make a class immutable below mentioned steps should be followed:

1. Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.

2. Make all fields final and private.

3. Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

4. If the instance fields include references to mutable objects, don’t allow those objects to be changed:-

– Don’t provide methods that modify the mutable objects.
– Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

public final class Person {
 private final String name;
 private final Integer age;
 public Person(final String name, final Integer age) {
  super();
  this.name = name;
  this.age = age;
 }
 public Integer getAge() {
  return age;
 }
 public String getName() {
  return name;
 }
}
Ninja Answered on 18th September 2018.
Add Comment