Home » Core Java » class » Immutable object example

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments