DEV Community

loading...

Immutable class in Java

aryan19694946 profile image aryan ・2 min read

In this article, we'll define the typical steps for creating an immutable class in Java and also shed light on the common mistakes which are made by developers while creating immutable classes.

visit the original article: https://www.java8net.com/2020/11/immutable-class-in-java.html

Steps to create Immutable class in java

  1. Make your class final, so that no other classes can extend it.
  2. Make all fields private so that direct access is not allowed.
  3. Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
  4. Special attention when having mutable instance variables 4.1) Inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real instance passed through the constructor. 4.2) Make sure to always return a clone copy of the field and never return the real object instance.

Implementation of Immutable class in java

class Address{
    private String houseNumber;
    private String street;
    private String city;
}

final class User {
    private final int id;
    private final String name;
    private final String email;
    private final Address address;

    /*
     * To clone the address.
     */
    private static Address cloneAddress(Address address) {
        return new ObjectMapper().convertValue(address, Address.class);
    }

    User(int id, String name, String email, Address address) {
        this.id = id;
        this.name = name;
        this.email = email;
        /*
         * Any field contains reference of any mutable 
                 * object must be
         * initialized with the cloned object
         */
        this.address = cloneAddress(address);
    }
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getEmail() {
        return email;
    }
    public Address getAddress() {
        /*
         * Getter method must return the reference of cloned object.
         */
        return cloneAddress(address);
    }
}
Enter fullscreen mode Exit fullscreen mode

Pre-defined Immutable class in java

  1. The string class represents the immutable object for the sequence of characters.
  2. Wrapper classes like Integer, Float, Long, etc. all represent the immutable object for the corresponding primitive type.
  3. java.util.UUID represents a unique 128-bit hexadecimal string.

Benefits of making an Immutable class in java

  1. Immutable objects are by default thread-safe.
  2. Immutable objects can easily be cached.
  3. Immutable objects are the best options to use as a key object in any map like HashMap.

visit the original article: https://www.java8net.com/2020/11/immutable-class-in-java.html

Discussion (0)

pic
Editor guide