Immutables and Java
What are immutables?
An immutable is a type that can’t be modified after it has been created.
The most common way to define an object in Java is by instantiating a class; Once the class is instantiated, we can modify its properties directly or by calling methods that modify them. Let’s look at an example of a mutable object:
1
2
3
public class MyClass {
public int value;
}
This is a very simple type that we can instantiate and modify:
1
2
MyClass obj = new MyClass();
obj.value = 4;
Immutables differ from these types in that once instantiated, they can’t be modified (Properties can’t be changed and there are no methods to modify them).