Total WebSite Views Count

immutable object

How to create a immutable object in Java? Count all benefits?

  • An immutable class is one whose state can not be changed once created.
  •  Here, state of object essentially means the values stored in instance variable in class whether they are primitive types or reference types.

To make a class immutable, below steps needs to be followed:
  1. Don’t provide “setter” methods or methods that modify fields or objects referred to by fields. Setter methods are meant to change the state of object and this is what we want to prevent here.
  2. Make all fields final and private. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.
  3. Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.
  4. Always remember that your instance variables will be either mutable or immutable. Identify them and return new objects with copied content for all mutable objects (object references). Immutable variables (primitive types) can be returned safely without extra effort.

AWS Services

AWS Services

Technology Selection & Evaluation Criteria

Technology Selection & Evaluation Criteria

Scale Cube - Scale In X Y Z Cube

Scale Cube - Scale In X Y Z Cube

Feature Post

AWS Services

About Me

About Me

Spring Cloud

Spring Cloud
Spring Cloud

Spring Cloud +mCloud Native + Big Data Archittect

Spring Cloud +mCloud Native + Big Data Archittect

ACID Transaction

ACID Transaction

Data Pipe Line Stack

Data Pipe Line Stack

Popular Posts