How can u make Your Own imumatebale class
Anonymous
We can achieve this by making everything in the class private. When someone tries to change any value, we don’t modify the existing object. Instead, we create a new object that has the old values plus the new value, and return the new object. This way, the original object retains its previous state. public final class Person { private final String name; private final int age; // Constructor public Person(String name, int age) { this.name = name; this.age = age; } // Getter methods public String getName() { return name; } public int getAge() { return age; } // "With" method to create a new object with a different name public Person withName(String newName) { return new Person(newName, this.age); } // "With" method to create a new object with a different age public Person withAge(int newAge) { return new Person(this.name, newAge); } }
Check out your Company Bowl for anonymous work chats.