Wednesday, August 15, 2012

Creating immutable object



Creating immutable object:


             String object are immutable objects, We can also create  immutable object in the following way...

package com.jsl.core;

final class Example{
 private final int count;
 
 public Example() {
  count=5;
 }

 public Example(int count){
  this.count=count;
 }

 public Example increment(int incrementVal){
  return new Example(this.count+incrementVal);
 }

 @Override
 public String toString() {
  return " "+count;
 }

}
public class ImmutableDemo {

  public static void main(String[] args) {

   Example e=new Example();
   System.out.println(e);
   System.out.println(e.increment(10));
   System.out.println(e);
  }
}

output:

5
15
5

No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...