May 21, 2020

How and why we create an immutable class in java - complete tutorial


Immutable class : A class whoes object once created, its value should not be changed. Mostly used for cacheing purpose. Example Java wrapper class


 Java Source code

/**
 *
 */
/**
 *  Java Sample to create an immutable class : Hotel
 */
package com.cfed.pattern.flyweight;

/**
 * @author Konzernites
 *
 */
// The class must be created as a final class in order to restrict the creation of child class
public final class Hotel {


// Members in the class must be declared as final
private final String hotelName;
private final String hotelChain;
private final int hotelId;


// private final int hotelId =9; // Final method can be initialized only once.


// A parameterized constructor , to set values to the object
public Hotel(int hotelId, String hotelName, String hotelChain) {
this.hotelId = hotelId;
this.hotelChain = hotelChain;
this.hotelName = hotelName;
}

// variable can be accessed only through getters method
public String getHotelName() {
return hotelName;
}

// No setters are allowed, the changing of value is restricted
public String getHotelChain() {
return hotelChain;
}

public int getHotelId() {
return hotelId;
}

}


/**
 *
 */
package com.cfed.pattern.flyweight;

/**
 * @author Teena
 *
 */
public class Main {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Hotel hotel = new Hotel(1, "Ibis", "IB");
System.out.println(hotel.getHotelName());

}

}


How can we create an Immutable class?

1. Create final class.
2. Declare member variables as final.
3. No setter methods.
4. Parameterized constructor.
5. Only getter methods are allowed.


Explanation

Making a class final restrict creation of child class

Declaring variables as final restrict the value to be changed. final variables can be initialized only once.

No setter methods allowed to restrict the change in value.

Parameterized constructor to set the value once and only at the time constructing its object.

Getters methods to get the value of the object.




No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments