• Register

1. Overview

In programming, an obj is taken immutable if its status cannot alter afterward it is produced. Java not only cares immutable obj but as a finest drill, it should be commonly used. In this post, we will take a gaze at how to generate immutable obj, their use suitcases, and some samples of immutable Classes.

The tools that we will use in the code samples are:

·         Java 8

·         Eclipse 4.10.0

2. Final keyword

 Immutability can be accomplished in attributes and obj. Originally, these are changeable, which means their status can alter. To create them unchallengeable we should use the final keyword when stating them. When we use the final keyword on a attribute or obj, then we must reset it else we will get a compilation mistake.

Here we understand  a sample of an unchallengeable obj where its attributes are stated final and class is stated final.

Immutable Class Java Sample

In this artefact, we will clarify what Immutable Class is in Java by samples.

final class Color1 {
     
    private final String name1;
    private final String hex1;
     
    public Color(String name1, String hex1) {
        this.name1 = name1;
        this.hex1 = hex1;
    }
     
    public String getName() {
        return name1;
    }
 
    public String getHex() {
        return hex1;
    }
}

The Color class has 2 attributes that are unchallengeable as they are stated final. These must be reset through the const. In this class, we understand that there are no setters as the state of the attributes can’t be improved. Let’s generate a new Color obj and also make it final.

ImmutableExample1:

public class ImmutableExample1 {
 
    public static void main(String[] args) {
        final Color1 red1 = new Color("RED", "#ff0000");
        System.out.printf("Colour %s hex1 is %s", red1.getName(), red1.getHex());
    }
}

Outcome:

 

Color RED hex1 is #ff0000

2,760 points
7 4