Wed, Nov 20, 2019
Read in 1 minutes
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.
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.
So, If you want to change the content fo the object, you have to create a new object.