Create Immutable Class in Java With Example?

Create Immutable Class in Java With Example?

immutable class means if its state cannot change after it is constructed. means once we created object we cant modify exisiting object.here state means instance variable values.

In Java String and all Wrapper classes are Immutable.

Rules to create Immutable class in java

  1. declare the class final,so that we cannot create subclass.
  2. make all fields final and private.so that we cannot change the values.
  3. dont write any setter methods in class

Example


package com.practice;

public final class Account {
private final int accountId;
private final String name;
public Account(int accountId, String name) {
super();
this.accountId = accountId;
this.name = name;
}
public int getAccountId() {
return accountId;
}
public String getName() {
return name;
}


}
-->