Immutable Class Example in Java

Immutable classes are the classes whose values never change once instantiated. There are many immutable classes i.e. String, Boolean, Byte, Short, Integer, Long, Float, Double etc . We can also create immutable class as below:

  • Declare the class final, so it can't be extended.
  • Make all the instance variables final and private. Fields declared private will not be accessible outside the class and making them final will ensure that you can not change them.
  • Don't provide any setter methods i.e. you have no option to change the value of the instance variable.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

Example to create Immutable class :
 public final class Student {
	// all instance variable should be private and final
	private final String studentName;
	private final long studentId;
	private final Date dateOfBirth;

	public Student(String studentName, long studentId, Date dateOfBirth) {
		this.studentName = studentName;
		this.studentId = studentId;
		this.dateOfBirth = dateOfBirth;
	}

	//String is immutable
	public String getStudentName() {
		return studentName;
	}

	//Long is immutable
	public long getStudentId() {
		return studentId;
	}

	//Date is mutable, so you may need to clone it 
	public Date getDateOfBirth() {
		return (Date) dateOfBirth.clone();
	}
	
}  


















Receive Latest Java Examples in Your Email: