- Immutable objects are those whose state cannot change after construction
- Examples: Integer and String
- Features
- Simple to construct, test, and us
- Automatically thread safe - No synchronization issue
- No need of copy construction
- No need of hash implementation
- How to make a class as immutable:
- Make sure that it cannot be inherited. Make it final.
- Keep constructor private.
- Make fields as final or private.
- No set methods to change the state of the object
Example:
Public final class Shape {
Private final int I;
Private final double j;
Public Shape(double a, int b) {
I = a;
J = b;
}
Public int getI() {
Return I;
}
Public double getJ() {
Return j;
}
Java Concepts
No comments:
Post a Comment