In Java, an immutable object is an object whose state cannot be modified after it is created. Once an immutable object is initialized, its internal data remains constant throughout its lifetime. Any operation that appears to modify an immutable object, such as calling a method like toUpperCase()
on a String
, actually results in the creation of a new object with the modified state, leaving the original object unchanged.
Key characteristics of immutable classes in Java:
- The class itself is declared
final
to prevent extension and potential creation of mutable subclasses. - All fields (instance variables) within the class are declared
private
to restrict direct access andfinal
to ensure they are assigned only once during object construction. - The class does not provide any public setter methods to modify the state of the object after creation.
- The class typically has a parameterized constructor to initialize all fields upon object creation.
- If the class contains references to mutable objects (like
Date
or collections), the constructor and any getter methods should perform deep copies to prevent external modification of the internal state.
Examples of immutable classes in Java's standard library:
String
: The most common example;String
objects are immutable.- Wrapper classes:
Integer
,Long
,Double
,Boolean
, etc., are all immutable. BigDecimal
andBigInteger
: These classes for arbitrary-precision numbers are also immutable.
Advantages of immutability:
- Immutable objects are inherently thread-safe as their state cannot be changed by multiple threads concurrently.
- The inability to modify an object's state eliminates a class of potential bugs related to unexpected state changes.
- If an object is used as a key in a
HashMap
orHashSet
, its hash code remains constant, ensuring correct behavior. - Immutable objects simplify code understanding and debugging due to their predictable behavior.
- Since their state never changes, immutable objects can be safely cached and reused.
Some other example to clear things,
String label = "Java";
label += " Programming";
System.out.println(label ); // Outputs "Java Programming"
Here, it might seem like label has been modified, but what actually happens under the hood is the creation of a new String object that holds "Java Programming" and then label is updated to refer to this new object. The original "Java" string remains unaltered in the string pool.
Reference from :- Google AI Review and Other resources
No comments:
Post a Comment