My goal is to make a Java object immutable. I have a class Student
. I coded it in the following way to achieve immutability:
public final class Student { private String name; private String age; public Student(String name, String age) { this.name = name; this.age = age; } public String getName() { return name; } public String getAge() { return age; } }
My question is, what is the best way to achieve immutability for the Student
class?
An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications.
An immutable object is an object that will not change its internal state after creation. Immutable objects are very useful in multithreaded applications because they can be shared between threads without synchronization. Immutable objects are always thread safe.
Your class is not immutable strictly speaking, it is only effectively immutable. To make it immutable, you need to use final
:
private final String name; private final String age;
Although the difference might seem subtle, it can make a significant difference in a multi-threaded context. An immutable class is inherently thread-safe, an effectively immutable class is thread safe only if it is safely published.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With