Immutable classes in Java


  1. Immutable objects are those whose state cannot change after construction
  2. Examples: Integer and String
  3. Features
    1. Simple to construct, test, and us
    2. Automatically thread safe  - No synchronization issue
    3. No need of copy construction
    4. No need of hash implementation
  4. How to make a class as immutable:
    1. Make sure that it cannot be inherited. Make it final.
    2. Keep constructor private.
    3. Make fields as final or private.
    4. 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

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...