How to create user defined immutable class in Java?

 

In this tutorial we will discuss about how to create immutable class in Java. When we say about immutable we will be remembered about important interview question like What is the difference between String and StringBuilder? We are familiar with String is a immutable and StringBuilder is mutable where values once assigned to String variable cannot the changed. 

Yes correct same way this is also interview question as how to create user defined immutable class in Java? Its simple just by Final modifier we can create our own immutable class. For this we need to make class, methods and member variable in the class as Final. By changing the modifier as final one cannot extend the class or override the methods and even cannot change the value once assigned to member variables. By this we can implement our own immutable class.

In below example code will show how to immutable class in Java.



public final class MyImmutableClass {
 
 private final String empName;
 
 public MyImmutableClass(String empName) {
  this.empName = empName;
 }
 
 public String getEmpName(){
  return this.empName;
 }
}



public class TestMyImmutable {
 public static void main(String[] args) {
  MyImmutableClass obj = new MyImmutableClass("Raj");
  
  /* 
   * Values once assigned cannot to changed by using set methods.
   * Just we can get the value assigned to the variable.
  */
  String empName = obj.getEmpName();
  System.out.println("Emp Name : "+empName);  
 }
}







2 comments:
Write comments