Skip to main content

Posts

Showing posts with the label Immutable Class

Why we must declare immutable class as Final? Why is an immutable class supposed to be final?

Why immutable class declared as final in Java? Immutable class means, once object is created it can not be changed.  Learn more about Immutable class in details : Create Immutable Class in Java | Advantages of immutable class in java   Now lets see why we must declare immutable class as final in Java. If immutable class does not defined as final then any other class can extends that class and change properties of that class and broke the objective of immutability. So final class is important in immutability. Lets see using example. Programming.java public class Programming {          private final String name;          public Programming(String name) {         this.name = name;     }     public String getName() {         return name;     }     @Override     public String toString() { ...

How to create Immutable Class or Object in Java? | Benefits of immutable class

Create Immutable Class in Java | Advantages of immutable class in java What is immutable class or object? In simple term, once the object of the class created its fields cannot be changed or modified. Like once Student object is created, it can not be changed. In java, all wrapper classes are immutable. like Boolean, String, Integer, Double, Long, Float. Why we need Immutable class? or Advantages of Immutable class When we does not want to change its fields after created. It is Thread safe. These objects are good for use as hash key (HashMap) Reference of immutable objects can be cached. How to create Immutable Class in Java? We can create Immutable class using simple following steps : Make class Final Make class fields Private and Final Do not write Setter method for fields   Create all arguments constructor Using above steps we can create Immutable class in Java. So lets go on code... // Final class final class Company {          // Private fiel...