How to make class as immutable in Java


1. All instance variables (state) must be set in the constructor alone. No other method should be provided to modify the state of the object. The constructor is automatically thread-safe and hence does not lead to problems.
2. It may be possible to override class methods to modify the state. In order to prevent this, declare the class as final. Declaring a class as final does not allow the class to be extended further.
3. All instance variables should be declared final so that they can be set only once, inside the constructor.
4. If any of the instance variables contain a reference to an object, the corresponding getter method should return a copy of the object it refers to, but not the actual object itself.

Example: 





public final class EmployeeModel {
//State
private final String firstName;
private final String lastName;
private final String SSN;
private final String address;
private final Car car;
//Constructor
public EmployeeModel(String fn, String ln, String ssn,
String addr, Car c) {
firstName = fn;
lastName = ln;
SSN = ssn;
address = addr;
car = c;
}
//Getters
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getSSN() {
return SSN;
}
public Car getCar() {
//return a copy of the car object
return (Car) car.clone();
}
public String getAddress() {
return address;
}
}

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email