Created
December 17, 2017 14:29
-
-
Save tamboer/b3d450b54ce52707915d1e49e50c1608 to your computer and use it in GitHub Desktop.
Immutable class java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| How Do We Create an Immutable Class | |
| In order to create an immutable class, you should follow the below steps: | |
| Make your class final, so that no other classes can extend it. | |
| Make all your fields final, so that they’re initialized only once inside the constructor and never modified afterward. | |
| Don’t expose setter methods. | |
| When exposing methods which modify the state of the class, you must always return a new instance of the class. | |
| If the class holds a mutable object: | |
| Inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real instance passed through constructor, this is to prevent the clients who pass the object from modifying it afterwards. | |
| Make sure to always return a clone copy of the field and never return the real object instance. | |
| https://dzone.com/articles/how-to-create-an-immutable-class-in-java | |
| */ | |
| public final class ImmutableStudent { | |
| private final int id; | |
| private final String name; | |
| public ImmutableStudent(int id, String name) { | |
| this.name = name; | |
| this.id = id; | |
| } | |
| public int getId() { | |
| return id; | |
| } | |
| public String getName() { | |
| return name; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment