What is an immutable object? How do you create one in Java?

What is an immutable object? How do you create one in Java?

Asked on November 13, 2018 in Java.
Add Comment


  • 3 Answer(s)

        Immutable classes are the type of class, whose object cannot be modified once created, it means any modification on immutable object will result in another immutable object. example understand immutable and mutable objects are, String and String buffer. While in case of mutable object like String buffer, any modification is done on object itself and no new objects can be created.
        The immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.

    How to write immutable class in Java

    1. State of immutable object cannot be modified after construction, any modification must result to the new immutable object.
    2. All fields of Immutable class should be final.
    3. Object must be properly constructed i.e. object reference must not leak during construction process.
    4. Object should be final in order to restrict sub-class for altering immutability of parent class.
    public final class Contacts {
     
        private final String name;
        private final String mobile;
     
        public Contacts(String name, String mobile) {
            this.name = name;
            this.mobile = mobile;
        }
     
        public String getName(){
            return name;
        }
     
        public String getMobile(){
            return mobile;
        }
    }
    

     

    Answered on November 13, 2018.
    Add Comment

    Immutable class is good for caching purpose because you don’t need to worry about the value changes. Other benefit of immutable class is that it is inherently thread-safe, so you don’t need to worry about thread safety in case of multi-threaded environment.

    Here I am providing a way to create immutable class in java via an example for better understanding.

    To create immutable class in java, you have to do following steps.
    1. Declare the class as final so it can’t be extended.
    2. Make all fields private so that direct access is not allowed.
    3. Don’t provide setter methods for variables
    4. Make all mutable fields final so that it’s value can be assigned only once.
    5. Initialize all the fields via a constructor performing deep copy.
    6. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

    To understand points 4 and 5, let’s run the sample Final class that works well and values doesn’t get altered after instantiation.

    FinalClassExample.java

    package com.journaldev.java;
    
    import java.util.HashMap;
    import java.util.Iterator;
    
    public final class FinalClassExample {
    
    	private final int id;
    	
    	private final String name;
    	
    	private final HashMap<String,String> testMap;
    	
    	public int getId() {
    		return id;
    	}
    
    
    	public String getName() {
    		return name;
    	}
    
    	/**
    	 * Accessor function for mutable objects
    Answered on January 18, 2019.
    Add Comment

    Immutable Class

    In order to create an immutable class, you should follow the below steps:

    1. Make your class final, so that no other classes can extend it.
    2. Make all your fields final, so that they’re initialized only once inside the constructor and never modified afterward.
    3. Don’t expose setter methods.
    4. When exposing methods which modify the state of the class, you must always return a new instance of the class.
    5. If the class holds a mutable object:
      • 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 constructor, this is to prevent the clients who pass the object from modifying it afterwards.
      • Make sure to always return a clone copy of the field and never return the real object instance.

    Simple Immutable Class

    Let’s follow the above steps and create our own immutable class (ImmutableStudent.java).

    package com.programmer.gate.beans;
    
    
    public final class ImmutableStudent {
    
    
        private final int id;
        private final String name;
    
    
        public ImmutableStudent(int id, String name) {
            this.name = name;
            this.id = id;
        }
    
    
        public int getId() {
            return id;
        }
    
    
        public String getName() {
            return name;
        }
    }

    The above class is a very simple immutable class which doesn’t hold any mutable object and never expose its fields in any way; these type of classes are normally used for caching purposes.

    Answered on January 18, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.