[JAVA] Variable / immutable object

I am a beginner, but I summarized it for personal study

Variable / immutable object

-The value of the field once set in the object is called ** mutable object ** for the object that can be changed later, and ** immutable ** for the object that cannot be changed.

-Instances of ** java.lang.String class ** and ** java.io.File class ** are typical examples of immutable objects. The value cannot be changed later If you want to handle a new value, you have to create a new instance, but ** "change the value of the variable (reference to the object)" **, not ** "change the state of the object" ** Don't, you should understand the difference

-To define an immutable object: (1) Do not provide a method that can change the internal state of an object (** setter method , etc.) ② ** Declare the class with final ** and guarantee that no method will be overridden (prevents state changes from subclasses) ③ ** Define all fields with "private final" ** ("final" is not mandatory, but you can more explicitly declare that it is an immutable class) (4) If a variable object is held inside, that object is not provided to the outside. ( getter method **, etc.) Also, do not change the value of the variable object internally.

Recommended Posts

Variable / immutable object
[Java] Difference between "final variable" and "immutable object"
variable
static variable
Immutable (immutable) List object conversion function in Java8
[Ruby] "Reference to object" and "Contents of variable"