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 method boolean nonzero(), that returns true if its field’s value is not zero and a third method ImmutableObject multiplier(int val) that returns a new ImmutableObject with its field multiplied by the given int value.
  • The class has a another method, static void function(ImmutableObject obj). The method gets an ImmutableObject and creates a new one, using the multiplier(int val) method of ImmutableObject. It also prints out the fields of both objects, using the read() method of ImmutableObject.
  • We create a new ImmutableObject and call the function(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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button