Mutable class in Java
A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of mutable and immutable objects. Depending on how they can be iterated, Java objects can either be changeable or immutable.
We will talk about Java's mutable as well as immutable objects in this part. We shall also observe how they differ from one another.
What are Mutable Objects?
Objects that can have their values altered after initialization are referred to as mutable objects. After the item is formed, we can alter its values for things like fields and states. For instance, StringBuilder, StringBuffer, Java.util.Date, etc.
heavily influenced by the language. Even changeable objects are not permitted in some of them.
Depending on the properties you expose on a class's public interface, several major languages have a high degree of default mutability. Making immutable objects is extremely difficult in at least a few popular programming languages, especially dynamic languages.
No new object will be generated when we modify an existing mutable object; instead, the value of an existing entity will change. The classes for these objects offer ways to alter them.
Mutable objects have get() and set() methods, which are known as getters and setters. Thread safety may or may not apply to the Mutable object.
What are Immutable Objects?
Immutable objects are those whose values cannot be altered once they have been initialised. Once an object is formed, nothing can be changed. Primitive objects like int, long, float, and double, all legacy classes, the Wrapper class, the String class, etc. are a few examples.
Immutable simply refers to something that cannot be altered or changed. Immutable objects cannot have their object values or states modified once they have been formed.
For immutable objects, there are no Setters (set () function) but only Getters (get () method).
Let's examine the process for developing classes for changeable and immutable objects.
How to create a Mutable class?
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
In Java, an immutable class indicates that once a object has been created, its content cannot be changed. All wrapper classes in Java, such as Integer, Boolean, Byte, and Short, as well as the String class, are immutable.
wrapping classes in Java, including Boolean, Character, Byte, Long, Float, Double, and Short, are immutable. Another immutable class is the string class.
The following two requirements must be met in order to create a changeable class:
- ways to change the field values
- The objects' getters and setters
Take into account the following changeable class example:
Mutablec.java
// importing all the requried packages
import java .io.*;
public class Mutablec {
private String str;
Mutablec (String str) {
this.str = str;
}
public String show () {
return str;
}
public void set (String cname) {
// Here, we can change the name.
this.str = cname;
}
// main method starts here
public static void main (String [] args) {
// object creation for the main class
Mutablec mc = new Mutablec("Manoj kumar");
// Show method to display the string
System.out.println(mc.show ());
// Here, we can use the set method to change the name.
mc.set("Mamilla Manoj");
// Show method to display the string
System.out.println(mc.show ());
}
}
Output:
Manoj kumar
Mamilla Manoj
Using the setName method, we are modifying the name value from the aforementioned example.
How to Make an Immutable Class
For a class to be considered immutable, the following requirements must be met:
- Final class, which cannot be extended and is marked as such.
- To prevent direct access to the fields, all fields should be private.
- Nobody sets
- All changeable fields ought to be marked as final so that after initialization, they cannot be iterated.
Consider the illustration below:
Exmpl1.java
// importing all the requried packages
import java. io.*;
public class Exmpl1 {
private final String str;
Exmpl1 (final String str) {
this.str = str;
}
public final String show () {
return str;
}
// main method starts here
public static void main (String [] args) {
// object creation for the main class
Exmpl1 obj = new Exmpl1("Jack");
// Show method to display the string
System.out.println(obj.show());
}
}
Output:
Jack
The discussion of changeable vs immutable classes and objects follows. Let's talk about how they differ from one another:
In Java, an immutable class indicates that once an object has been created, its content cannot be changed. All wrapper classes in Java, such as Integer, Boolean, Byte, and Short, as well as the String class, are immutable. We may even design our own immutable class. Read through the immutability's qualities before moving on so that you may implement it with confidence. Here are the prerequisites:
- In order to prevent the creation of child classes, the class should be designated as final.
- To prevent direct access, data members of the class should be made private.
- To prevent value changes after object creation, data members in classes must be marked as final.
- To prevent data members from being changed by an object reference, a parameterized function Object () { [native code] } should do a deep copy initialization of all the fields.
- Instead of returning the real object reference, getter methods should execute a deep copy of the object to return a copy.
Difference between Mutable and Immutable Objects
Key distinctions between Java's changeable and immutable objects include the following:
- Without creating a new object, the changeable objects can be altered to every value or state. In contrast, once an immutable object has been created, it cannot be modified in value or state. With immutable objects, a new object is created each time the state of a object is changed.
- The ability to modify an object's content is provided by mutable objects. In contrast, immutable entities do not offer a way to modify the values.
- The setters & getters are supported by the mutable objects. In contrast, only setters, not getters, are supported by immutable objects.
- Immutable entities are thread-safe by default, whereas mutable objects might or might not be thread-safe.
- StringBuffer, Java.util.Date, StringBuilder, and so on. are examples of mutable classes. Legacy classes, wrapper classes, the String class, etc. are examples of immutable objects.
Think about the table below:
Mutable | Immutable |
After startup, mutable objects can have their value changed. | When an immutable entity is started, its values cannot be changed. |
The state is modifiable. | There is no way to alter the state. |
No new variables are declared in changeable objects. | When the value of an immutable object is changed, a new object is created. |
It offers ways to modify the object. | It does not offer a way to modify an object's value. |
The get () & set () methods are offered for interacting with the object. | Only the get () function is supported for passing object values. |
Thread safety could or might not apply to mutable classes. | Thread safety exists for immutable classes. |
Getter and setter methods, as well as methods for changing fields, are necessary for developing mutable classes. | Final class, hidden fields, and final mutable objects are necessary for making an immutable class. |
Why are Strings in Java Immutable?
Due to its widespread usage in Java programmes, the String class in Java is a rather unique one. It is immutable in order to improve security and performance. Let's examine it in greater detail:
Strings in Java employ the literal idea. Consider an object with numerous reference variables. A reference variable's value in such a case would modify the value of the entire entity with all its values.
In addition to the causes listed above, the following factors also contribute to the String's immutability:
Immutable objects are extremely straightforward, require no synchronisation, and are naturally thread-safe. However, since immutable objects are useful as construction blocks for other things, we must take extra care of them.
The String is typically made the final object by developers so that it cannot be changed afterwards.
Conclusion
After talking about changeable and immutable entities in Java, we clearly grasp both types of objects and classes. Additionally, we learned how to develop mutable and immutable classes.
Immutable objects can have their content and state modified after being created, and they might or might not be thread-safe. In contrast, immutable objects are thread-safe by default and cannot have their state or value modified.