Java Immutable Classes

Source: Internet
Author: User

    • What is an immutable class
    1. When you obtain a reference to this class, you cannot change the contents of this class;
    2. Once an instance of an immutable class is created, its member variables cannot be modified;

  

    • How to create immutable classes
    1. Member variables are private permissions
    2. does not provide an external interface that alters member variables, that is, the Set method
    3. 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)
    4. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.