Immutable Objects in java

Wed, Nov 20, 2019

Read in 1 minutes

What is immutable?

If you cannot change the content of the object, then that is called immutable objects. String and all other wrapper classes Integer, Double are immutable.

How to create custom immutable objects?

public final class CreditCard {
	private final Long cardNumber;
	private  final String cardHolderName;
public CreditCard(Long cardNumber, String cardHolderName) {
		super();
		this.cardNumber = cardNumber;
		this.cardHolderName = cardHolderName;
	}
	public Long getCardNumber() {
		return cardNumber;
	}
	public String getCardHolderName() {
		return cardHolderName;
	}
	public static void main(String[] args) {
		CreditCard card= new CreditCard(1243536L, "rty");
		System.out.println(card.cardHolderName);
		System.out.println(card.cardNumber);
		//card.cardHolderName="xxxx";
	}
}

If you try a change the content of the object, you will get below error.

output_immutable_objects

So, If you want to change the content fo the object, you have to create a new object.