class
Immutable object example
With this example we are going to demonstrate how to create and use an immutable object. Immutable objects are objects whose state cannot change after construction. In short, we have created an immutable object, as described below:
- We have created a a class,
ImmutableObject
, that has an int field. It has a constructor using its field. - The class has a method
int read()
that returns the value of its field, a methodboolean nonzero()
, that returns true if its field’s value is not zero and a third methodImmutableObject multiplier(int val)
that returns a newImmutableObject
with its field multiplied by the given int value. - The class has a another method,
static void function(ImmutableObject obj)
. The method gets anImmutableObject
and creates a new one, using themultiplier(int val)
method ofImmutableObject
. It also prints out the fields of both objects, using theread()
method of ImmutableObject. - We create a new
ImmutableObject
and call thefunction(ImmutableObject obj)
, to print out the values of the fields of the two objects created.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class ImmutableObject { private int data; public ImmutableObject(int initVal) { data = initVal; } public int read() { return data; } public boolean nonzero() { return data != 0; } public ImmutableObject multiplier(int val) { return new ImmutableObject(data * val); } public static void function(ImmutableObject obj) { ImmutableObject m = obj.multiplier(4); System.out.println("obj = " + obj.read()); System.out.println("m = " + m.read()); } public static void main(String[] args) { ImmutableObject object = new ImmutableObject(32); System.out.println("object = " + object.read()); function(object); System.out.println("object = " + object.read()); } }
Output:
object = 32
obj = 32
m = 128
object = 32
This was an example of how to create and use an immutable object in Java.