Home »

Immutable Objects in Java

Immutable Objects are those objects whose state can not be changed once they are created, example String class is immutable class. Immutable objects can not be modified so they are also thread safe in con current execution.

Features of immutable classes:

  • simple to construct
  • automatically thread safe
  • good candidate for Map keys and Set as their inter sate would not change while processing
  • dont need implementation of clone as they always represent same state

Keys to write immutable class:

  • make sure class can not be overridden
  • make all member variable private & final
  • do not give their setter methods
  •  object reference should not be leaked during construction phase

Example of simple immutable class :

        public final class StudentEnroll{
	    private final String name;
	    private final String regNo;

	    public StudentEnroll(String name, String regNo) {
	        this.name = name;
	        this.regNo = regNo;

	    public String getName(){
	        return name;

	    public String getRegNo(){
	        return regNo;

1 Comment

  1. […] Read more about immutable class in my another section :Guidelines to write immutable classes. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: