How to make Java classes immutable

Source: Internet
Author: User

How to make Java classes immutable

Immutable class: Once created, the status cannot be changed
There are many rules for creating immutable classes. The following describes these rules one by one:
Directory

Guide to defining the benefits of an immutable class

Benefits of defining immutables

The structure is simple, so it is convenient to test and use immutable classes. It is naturally thread-safe, and there is no need to care about multithreading and synchronization issues. clone is not required to implement delayed loading, cache its return value because it is unchangeable and can be used for Map keys and Set elements (set elements cannot be repeated). When used as an attribute, deep clone is not required.

How to make classes immutable

In the Java document, there is a guide on how to define an immutable class: click here

The setter method is not provided. The setter method is used to modify attributes and object references.
This principle illustrates that the setter method is not provided for all variable attributes defined by your class. The setter method means that you can change the status of this attribute. The setter method must be blocked. Add private and final for all attribute Modifiers
This is another way to add immutable attributes. The attribute declaration is private. In order not to be accessible outside the class, the final modifier prevents you from changing them at will. The subclass rewriting method is not allowed.
The simplest way to declare a class is final. The final class cannot be overwritten. Pay special attention to variable objects in attributes.
Always remember your object variables, either variable or immutable (this sentence seems nonsense ..), The variable object is identified, the content of the variable object is copied, and a new object is created and assigned to it. This ensures that the variable object is immutable by directly copying the object content, keep data immutable

To be elegant, define a private constructor and construct an object through the factory Method

I just want to say it's too abstract, so I 'd like to take a look at it.

import java.util.Date;/*** Always remember that your instance variables will be either mutable or immutable.* Identify them and return new objects with copied content for all mutable objects.* Immutable variables can be returned safely without extra effort.* */public final class ImmutableClass{    /**    * Integer class is immutable as it does not provide any setter to change its content    * */    private final Integer immutableField1;    /**    * String class is immutable as it also does not provide setter to change its content    * */    private final String immutableField2;    /**    * Date class is mutable as it provide setters to change various date/time parts    * */    private final Date mutableField;    //Default private constructor will ensure no unplanned construction of class    private ImmutableClass(Integer fld1, String fld2, Date date)    {        this.immutableField1 = fld1;        this.immutableField2 = fld2;        this.mutableField = new Date(date.getTime());    }    //Factory method to store object creation logic in single place    public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)    {        return new ImmutableClass(fld1, fld2, date);    }    //Provide no setter methods    /**    * Integer class is immutable so we can return the instance variable as it is    * */    public Integer getImmutableField1() {        return immutableField1;    }    /**    * String class is also immutable so we can return the instance variable as it is    * */    public String getImmutableField2() {        return immutableField2;    }    /**    * Date class is mutable so we need a little care here.    * We should not return the reference of original instance variable.    * Instead a new Date object, with content copied to it, should be returned.    * */    public Date getMutableField() {        return new Date(mutableField.getTime());    }    @Override    public String toString() {        return immutableField1 +" - "+ immutableField2 +" - "+ mutableField;    }}

Verify the above immutable classes:

import java.util.Date;public class MainTest{    public static void main(String[] args)    {        ImmutableClass im = ImmutableClass.createNewInstance(100,"test", new Date());        System.out.println(im);        tryModification(im.getImmutableField1(),im.getImmutableField2(),im.getMutableField());        System.out.println(im);    }    private static void tryModification(Integer immutableField1, String immutableField2, Date mutableField)    {        immutableField1 = 10000;        immutableField2 = "test changed";        mutableField.setDate(10);    }}

The output result is as follows:
100-test-Tue Jun 09 23:14:01 CST 2015
100-test-Tue Jun 09 23:14:01 CST 2015

The output shows that even if the object variable is changed through object reference, the value remains unchanged, so the class is an immutable class.

Click here
Related materials: click here
Official Tutorial: click here

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.