FastFoodCoding

Login


Connect with one of the following accounts





Login

Please wait while we redirect...

Views: 50   



Below are mandatory steps to create the immutable class in java

  1. Declare the class as final, no one will extend it.
  2. Make all properties/fields in the class as final and private, so there is no scope to modify the fields.
  3. Don’t provide “setter” methods, methods that modify fields or objects referred to by fields.
  4. Force to construct an object of the class directly, do not use any setter methods

Following is some sample code.



final class MyImmutableClass 
{

    private final String name;
    private final int age;
    private final String address;

    public MyImmutableClass(String personName,int personAge,String personAdress) {
        name = personName;
        age = personAge;
        address = personAdress;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getAddress() {
        return address;
    }

}
public class ImmutableTest {
    public static void main(String[] args) {
        MyImmutableClass immutable = new MyImmutableClass("Mike", 25, "Astralia");
    }
}

Benefits of making a class immutable

  • Immutable objects are automatically thread-safe.
  • Once created the state of the immutable object can not be changed so there is no chance to get them into an inconsistent state.
  • The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
  • Most important point is we can use immutable objects is as the keys of a map.

Below are Default immutable classes in java

  • All wrapper classes
    String, Integer, Boolean, Character, Byte, Short, Long, Float, Double



On By


Top Tutorials

Top Questions

Top Articles

Top Blogs

Top News