• August 27, 2014
  • Core Java
  • Comments Off on How to write Immutable class in java

How to write 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. 1. Make final class so that it cannot inherit.
  2. 2. Object state is made up of its properties, declare all properties final. So that its properties value will remain constant.
  3. 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 javawithease
 */
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. 1. Objects are thread safe by default.
  2. 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.

Related Topics:

String handling in java with example.
String Comparison in java with example.
String concatenation in java with example.
Substring in java with example.
How to write Immutable class in java with example.
toString() method in java with example.
Commonly used methods of String Class with example.
charAt(int index) String function in java with example.
startsWith(String prefix) and endsWith(String suffix) String functions in java.
indexOf(String str) and lastIndexOf(String str) String functions in java.
toLowerCase() and toUpperCase() String functions in java.
intern() String functions in java with example.
length() String functions in java with example.
trim() String functions in java with example.

 


Comments are closed.