CodesJava

Easy learning with example program codes

Immutable class in java


All wrapper classes and String class are immutable classes.

You can write your own immutable class, when creating immutable class just keep in mind that after creating an object of this class object can’t be modified. Any change in existing object result into new object.

  1. Make final class so that it cannot inherit.
  2. Object state is made up of its properties, declare all properties final. So that its properties value will remain constant.
  3. Object properties value can be set using setter methods, so only define getter methods for all properties.

Example:

ImmutableClassExample.java

/**
 * This program is used to create a immutable class.
 * @author codesjava
 */
final class Student{
	//declare all properties final.
	final String rollNo;	
 
	public Student(String rollNo){
		this.rollNo = rollNo;
	}
 
	//only create getter method.
	public String getRollNo() {
		return rollNo;
	}
}
 
public class ImmutableClassExample {
	public static void main(String args[]){
		//creating Student object. 
		Student obj = new Student("MCA/07/06");
 
		System.out.println(obj.getRollNo());
	}
}

Output:

MCA/07/06

Download this example.

Advantages/Benefits of immutable class.

  1. Objects are thread safe by default.
  2. No need to synchronize immutable objects explicitly.

Disadvantages of immutable classes.

As discussed any change in immutable object result into a new object, hence result in unnecessary garbage.
 
Next Topic: toString() method in java with example.
Previous Topic: Substring in java with example.

 

Please follow and like us:
Posted in Java   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki