Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Create Immutable Class in Java

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 462
    Comment on it

    How to create Immutable class in java

    Immutable class is a class which once created, its contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe. All wrapper classes in java.lang are immutable String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

    1. Create a final class.

      public final class FinalPersonClass { 

      }
    2. Set the values of properties using constructor only.

      public final class FinalPersonClass { 
      public FinalPersonClass(final String name, final int age) { this.name = name; this.age = age;
      } }

    3. Make the properties of the class final and private

      public final class FinalPersonClass { 
                  private final String name; 
                  private final int age; 
                  public FinalPersonClass(final String name, final int age) { 
                      super(); 
                      this.name = name; 
                      this.age = age; 
                  }
          } 

    4. Do not provide any setters for these properties.

      public final class FinalPersonClass { 
              private final String name; 
              private final int age; 
              public FinalPersonClass(final String name, final int age) { 
                  super(); 
                  this.name = name; 
                  this.age = age; 
              }
              public int getAge() { 
                  return age; 
              } 
               public String getName() { 
                   return name; 
               } 
      }

    5. If the instance fields include references to mutable objects, don't allow those objects to be changed:

    6. Don't provide methods that modify the mutable objects.
    7. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: