Create an Immutable Class in Java

Exercise:

Write a Java Program to create a immutable class.

Click Here to View the Solution!
final class Immutable {
    private String name;
    private String purpose;
    Immutable(String name,String purpose) {

        // initialize the immutable variables
        this.name = name;
        this. purpose = purpose;
    }

    // private getter methods
    public String getName() {
        return name;
    }
    public String getPurpose() {
        return purpose;
    }
}
public class Main {
    public static void main(String[] args) {

        // create object of Immutable
        Immutable obj = new Immutable("CodeOfCode","A programming website");
        System.out.println("Name: " + obj.getName());
        System.out.println("Date: " + obj.getPurpose());
    }
}
Click Here to View the Output!
Name: CodeOfCode
Date: A programming website
Click Here to View the Explanation!
  • This program depicts the procedure to create a type of class, with immutable properties.
  • To carry out this task, we first declare a class immutable, but add a keyword final before class name.
  • After that, two class members (private) are declared, name and purpose with String type.
  • Then we have two getter methods that’ll return the values created during object instantiation.
  • One thing should be noticed, is that there are no setter methods.
  • This is so, because classes declared with final key word do not get to set values; rather the values are initialized by the class constructor.
  • Moreover, final classes are not allowed to be extended.
  • As the class variables are private, hence they cannot be used directly.
  • Rather, they are accessed by class functions only just like in this example.