• 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.

  1. package com.instaceofjava;

  2.  
  3. public final class ImmutableClass{
  4.   
  5. private final int a;
  6. private final int b;
  7.  
  8. ImmutableClass( int x, int y){
  9.  
  10.  a=x;
  11.  b=y; 

  12.  
  13. public getA(){
  14.  
  15.  return a;

  16. }
  17.  
  18. public getB(){
  19.  
  20.  return b;

  21. }
  22.  
  23. public static void main(String[] args) {
  24.  
  25. ImmutableClass obj= new ImmutableClass(10,20);
  26.  
  27. System.out.println("a="+obj.getA());
  28.  
  29. System.out.println("b="+obj.getB());
  30.  
  31. }
  32. }
Output:

  1. a=10
  2. b=20


String class in java: Immutable


  1. public final class String
  2.         implements java.io.Serializable, Comparable<String>, CharSequence
  3. {  
  4.   
  5. //String class variables

  6.   private final char value[];
  7.   private final int offset;
  8.   private final int count;
  9.   private int hash; // Default to 0
  10.   private static final ObjectStreamField[] serialPersistentFields =
  11.       new ObjectStreamField[0];
  12.   
  13. //String class constructor
  14. public String(String original) {
  15.  
  16.             int size = original.count;
  17.              char[] originalValue = original.value;
  18.              char[] v;
  19.              if (originalValue.length > size) {
  20.                 // The array representing the String is bigger than the new
  21.               // String itself.  Perhaps this constructor is being called
  22.                 // in order to trim the baggage, so make a copy of the array.
  23.                  int off = original.offset;
  24.                 v = Arrays.copyOfRange(originalValue, off, off+size);
  25.             } else {
  26.                  // The array representing the String is the same
  27.                  // size as the String, so no point in making a copy.
  28.                  v = originalValue;
  29.            }
  30.             this.offset = 0;
  31.              this.count = size;
  32.             this.value = v;
  33.         } 

  34. }



Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu