- What is an immutable class
- When you obtain a reference to this class, you cannot change the contents of this class;
- Once an instance of an immutable class is created, its member variables cannot be modified;
- How to create immutable classes
- Member variables are private permissions
- does not provide an external interface that alters member variables, that is, the Set method
- All methods are not overloaded and are implemented in two ways: 1) All methods plus the final keyword (weakly immutable Class) 2) Use final class (strong non-volatile class)
- If the member variable of the class is a variable subclass, then in the initialization process, the variable subclass needs to be deeply copied;
Example:
1 Public classImmutedemo {2 PrivateString name;//String is an immutable class3 PrivateDate date;//Date is a mutable class4 5 PublicImmutedemo (String name,date Date) {6 This. Name =name;7 This. Date =NewDate (Date.gettime ());//Copy the input object8 //date.settime (2101); Changes the input object without affecting the value of the member date9 }Ten One PublicString GetName () { A returnname; - } - the PublicDate getDate () { - return NewDate (Date.gettime ()); - } - + Public Static voidMain (string[] args) { -Date Date =NewDate (); +Immutedemo Immutedemo =NewImmutedemo ("Zhang San", date); A } at } -
Java Immutable Classes