All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Create Immutable Class In Java With Mutable Object

Last Updated : Mar 11, 2024

How To Create Immutable Class In Java With Mutable Object

In this article we will show you the solution of how to create immutable class in java with mutable object, immutable objects are entities whose initialised states cannot be modified. Depending on the situation, it may be required to create an immutable class.

For instance, all primitive wrapper classes in Java, including Boolean, Character, Byte, Long, Float, Double, and Short, are immutable. Another immutable class is the string class.

Step By Step Guide On How To Create Immutable Class In Java With Mutable Object :-

The steps below must be completed in order to construct a unique immutable class.

  • Always Declare the class to be final to prevent any extensions.
  • Make all fields private to prevent immediate access.
  • Don't offer setter methods for variables, which prevents them from being changed.
  • Make all fields that can be modified final so that their values can only be changed once.
  • Create a function Object() { [native code] } that performs the deep copy initialization for all the fields.
  • Instead of returning the real object reference, clone the objects in the getter methods and return a copy.
  • Don't allow mutable objects to be altered if the instance fields include references to them.
  • Offer no techniques to change the mutable objects.

Keep references to the changeable objects private. Never keep a reference to a constructor-passed changeable object from the outside world. Make copies as necessary, then store references to the copies.

Likewise, if possible, make clones of our internal mutable objects to avoid returning the originals when calling methods.

Making a simple immutable class is pretty simple, but as you become more involved, you'll run into a lot of difficulties. Because of this, immutability is a particularly popular interview subject for Java engineers at the mid-level.

This post is a follow-up to How to Develop Immutable Classes in Java, where we examined how to create fundamental immutable classes using both a traditional technique and an approach based on the Builder Design Pattern.

// Employee.java
final class Employee {
   private final String empName;
   private final int age;
   private final Address address;
   public Employee(String name, int age, Address address) {
      super();
      this.empName = name;
      this.age = age;
      this.address = address;
   }
   public String getEmpName() {
      return empName;
   }
   public int getAge() {
      return age;
   }
   /* public Address getAddress() {
      return address;
      }
   */
   public Address getAddress() throws CloneNotSupportedException {
      return (Address) address.clone();
   }
}
// Address.java
class Address implements Cloneable {
   public String addressType;
   public String address;
   public String city;
   public Address(String addressType, String address, String city) {
      super();
      this.addressType = addressType;
      this.address = address;
      this.city = city;
   }
   public String getAddressType() {
      return addressType;
   }
   public void setAddressType(String addressType) {
      this.addressType = addressType;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String getCity() {
      return city;
   }
   public void setCity(String city) {
      this.city = city;
   }
   public Object clone() throws CloneNotSupportedException {
      return super.clone();
   }
   @Override
   public String toString() {
      return "Address Type - "+addressType+", address - "+address+", city - "+city;
   }
}
// MainClass.java
public class MainClass {
   public static void main(String[] args) throws Exception {
      Employee emp = new Employee("Vasav", 25, new Address("Home", "Jaipur", "Rajasthan"));
      Address address = emp.getAddress();
      System.out.println(address);
      address.setAddress("Hi-tech City");
      address.setAddressType("Office");
      address.setCity("Hyderabad");
      System.out.println(emp.getAddress());
   }
}
  1. Firstly, we will create a final class Employee with three data members, String, int and Address.
  2. Then we will use This keyword to call empName, age and address.
  3. Then we will create a method public String getEmpName()
  4. Then we will create two more methods getAge() and getAddress().
  5. Then we will implement cloneable Interface
  6. Then we will create three string data types Addresstype,address and city.
  7. Then we will use this keyword to call all three data types.
  8. Then we will go to Main Class phase.
  9. Here we will create Main class named MainClass
  10. Main method and an exception will be thrown
  11. Then we will create object of the class Employee using new keyword and a default constructor will be called.
  12. Then we will call emp.getAddress method.
  13. We will print the statement address,set.address “high tech city”.
  14. In the last printing statement emp.getAddress.
  15. Lastly, run the code

Conclusion :-

So, this is the end of the article. In this article we learned about creating immutable class in java with mutable object. In the next segment we will learn about reversing a string in Java.

I hope this article on how to create immutable class in java with mutable object helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪