Java — Creation of Our Own Immutable Class | Code Factory

package com.example.string;/**
* @author code.factory
*/
final class ImmutableExample {

private int i;

ImmutableExample(int i) {
this.i = i;
}

public ImmutableExample modify(int i) {
if(this.i == i) {
return this;
} else {
return new ImmutableExample(i);
}
}

public static void main(String... args) {
ImmutableExample ix1 = new ImmutableExample(10);
ImmutableExample ix2 = ix1.modify(100);
ImmutableExample ix3 = ix1.modify(10);
System.out.println(ix1 == ix2); // false
System.out.println(ix1 == ix3); // true
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store