Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make immutable Java object

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?

like image 690
Ruchira Gayan Ranaweera Avatar asked Aug 12 '13 18:08

Ruchira Gayan Ranaweera


People also ask

Can object be immutable in Java?

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.

What is immutable object can you write immutable object in Java?

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.


1 Answers

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.

like image 61
assylias Avatar answered Sep 18 '22 23:09

assylias