- In Java String and all wrapper classes are immutable classes.
- So how to create custom immutable class in java?
- Lets see how to make a class object immutable.
Immutable class:
- Make class final so that it should not be inherited.
- All the variables should be private so should not be accessible outside of class.
- Make all variables final so that value can not be changed.
- A constructor to assign values to variables in class.
- Do not add any setter methods.
1. Java Program to create custom immutable class object in java.
- package com.instaceofjava;
- public final class ImmutableClass{
- private final int a;
- private final int b;
- ImmutableClass( int x, int y){
- a=x;
- b=y;
- }
- public getA(){
- return a;
- }
- public getB(){
- return b;
- }
- public static void main(String[] args) {
- ImmutableClass obj= new ImmutableClass(10,20);
- System.out.println("a="+obj.getA());
- System.out.println("b="+obj.getB());
- }
- }
- a=10
- b=20
String class in java: Immutable
- public final class String
- implements java.io.Serializable, Comparable<String>, CharSequence
- {
- //String class variables
- private final char value[];
- private final int offset;
- private final int count;
- private int hash; // Default to 0
- private static final ObjectStreamField[] serialPersistentFields =
- new ObjectStreamField[0];
- //String class constructor
- public String(String original) {
- int size = original.count;
- char[] originalValue = original.value;
- char[] v;
- if (originalValue.length > size) {
- // The array representing the String is bigger than the new
- // String itself. Perhaps this constructor is being called
- // in order to trim the baggage, so make a copy of the array.
- int off = original.offset;
- v = Arrays.copyOfRange(originalValue, off, off+size);
- } else {
- // The array representing the String is the same
- // size as the String, so no point in making a copy.
- v = originalValue;
- }
- this.offset = 0;
- this.count = size;
- this.value = v;
- }
- }
No comments