1. Initial definitions of mutable and immutable objects:
Variable class: When you get an instance reference of this class, you can change the content of this instance.
Immutable class: When you obtain an instance reference of this class, you cannot change the content of this instance. Once an instance of an immutable class is created, the value of its inner member variable cannot be modified.
2. How to create an unchangeable class:
. All members are private
. Do not provide methods for changing members, such as setxxxx.
. Make sure that all methods are not overloaded. There are two methods: Use final class (strongly immutable class), or add final (weak immutable class) to all class methods ).
. If a class member is not a primitive or an immutable class, you must use the in-depth clone method when initializing (in) or getting (out) the member, to ensure that the class is not changeable.
3. An example
Import java. util. date;
Public final class brokenperson
{
Private string firstname;
Private string lastname;
Private date DOB;
Public brokenperson (string firstname, public betterperson (string firstname,
String lastname, date DOB) string lastname, date DOB)
{{
This. firstname = firstname; this. firstname = firstname;
This. lastname = lastname; this. lastname = lastname;
This. DOB = DOB; // error this. DOB = new date (DOB. gettime (); // correct
}}
Public String getfirstname ()
{
Return this. firstname;
}
Public String getlastname ()
{
Return this. lastname;
}
Public date getdob ()
{{
Return this. DOB; // error return new date (this. DOB. gettime (); // correct
}}
}
4. JDK variable classes and immutable classes
Primitive variables: Boolean, byte, Char, double, float, integer, long, short
JDK's immutable class: Boolean, byte, character, double, float, integer, long, short, string in JDK's Java. lang package.
Variable stringbuffer class
Java. util. Date variable class