1.

Create Immutable class in Java

Answer»

An immutable class in Java is one that cannot change its state after its construction. Some of the requirements to create an immutable class in Java are GIVEN as FOLLOWS:

  1. The class should be final so that other classes can’t extend it.
  2. All the fields of the class should be final so that they are only initialized one time inside the constructor.
  3. Setter methods should not be exposed.
  4. A new instance of the class should be returned if any methods that MODIFY the state of the class are exposed.
  5. If there Is a mutable object inside the constructor, only a clone copy of the passed argument should be USED.

An example that demonstrates the creation of an immutable class in Java is given as follows:

public final class Employee {    final int empNum;    final String name;    final int salary;    public Employee(int empNum, String name, int salary)    {        this.empNum = empNum;        this.name = name;        this.salary = salary;    }    public int empNumReturn()    {        return empNum;    }    public String nameReturn()    {        return name;    }    public int salaryReturn()    {        return salary;    } }

The class given above is a basic immutable class. This class does not contain any mutable object or any setter methods. This type of a basic class is normally used for caching purposes.



Discussion

No Comment Found