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