DEV Community

Cover image for Immutable Objects and Classes
Paul Ngugi
Paul Ngugi

Posted on

Immutable Objects and Classes

You can define immutable classes to create immutable objects. The contents of immutable objects cannot be changed. Normally, you create an object and allow its contents to be changed later. However, occasionally it is desirable to create an object whose contents cannot be changed once the object has been created. We call such an object as immutable object and its class as immutable class. The String class, for example, is immutable. If you deleted the setter method in the
CircleWithPrivateDataFields class, the class would be immutable, because radius is private and cannot be changed without a setter method.

If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily immutable. For example, the following Student class has all private data fields and no setter methods, but it is not an immutable class.

  public class Student {
  private int id;
  private String name;
  private java.util.Date dateCreated;

  public Student(int ssn, String newName) {
  id = ssn;
  name = newName;
  dateCreated = new java.util.Date();
 }

 public int getId() {
 return id;
 }

 public String getName() {
 return name;
 }

 public java.util.Date getDateCreated() {
 return dateCreated;
 }
 }
Enter fullscreen mode Exit fullscreen mode

As shown in the following code, the data field dateCreated is returned using the getDateCreated() method. This is a reference to a Date object. Through this reference, the content for dateCreated can be changed.

public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, "John");
java.util.Date dateCreated = student.getDateCreated();
dateCreated.setTime(200000); // Now dateCreated field is changed!
}
}

For a class to be immutable, it must meet the following requirements:

  • All data fields must be private.
  • There can’t be any mutator methods for data fields.
  • No accessor methods can return a reference to a data field that is mutable

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

AI Agent image

How to Build an AI Agent with Semantic Kernel (and More!)

Join Developer Advocate Luce Carter for a hands-on tutorial on building an AI-powered dinner recommendation agent. Discover how to integrate Microsoft Semantic Kernel, MongoDB Atlas, C#, and OpenAI for ingredient checks and smart restaurant suggestions.

Watch the video 📺

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay