Immutable class is very simple and interesting topic, but sometimes people get confused while talking about immutability and immutable class creation in detail. Today I will try to explain immutable class definition, creation and key points to remember when we are creating an immutable class.
Immutable class - State of immutable class object can not be changed after creation. String in most used immutable class in Java. All wrapper classes in java are immutable classes.
Benefits of Immutable class - Immutable classes provides some very important features over mutable class, that are-
- Immutable classes are by default thread-safe, because after creation state of object can not be changed. So there is no need to take care about thread safety when used in multi-threaded environment.
- Other than thread-safety immutable classes are also very good members to use in caching, without caring about value changes.
How to create immutable class - There are some very simple step to create an immutable class. Let's see the steps to create immutable class.
- Make the class final and all the attributes private. So that class can not be extended by any other class and attributes can not be accessed directly. In Java String is a final class and all string attributes are private.
- Don't create setter method for any attribute. So that after object creation no one can set a new value to any attribute.
- If there is any mutable object reference is present in class, make them final. So they can not be changed after creation.
- Initialize the object through constructor, and don't use any mutable reference directly. E.g. If our class having any collection or Date instance variable, than we should not assign the values passed in constructor directly to class's instance variable, because if values in referenced collection or date object are changed from outside it will be changed in immutable class also, which will break the immutability feature. So create a local copy with deep cloning and assign to the mutable instance variable is class.
- In getter methods also never return the actual object directly, instead return a copy.
I hope everything about immutable classes is clear now. But if you have any question please comment below I will try to resolve ASAP.
Check below links also-
Method overloading versus method overriding in Java
Difference between Interface and Abstract class
Difference between Abstraction and Encapsulation
Method overloading versus method overriding in Java
Difference between Interface and Abstract class
Difference between Abstraction and Encapsulation
Difference between Comparable and Comparator in Java
***********************Keep studying***********************
No comments:
Post a Comment