Java Immutable Class

Source: Internet
Author: User

mutable classes: After an instance of a class is created, you can also modify the contents of the instance.

For example, to create a 3*3 matrix, if Set function is set, you can change the size of the corresponding position element with set in main.

Immutable classes: When an instance of a class is established, the State does not change and the member variable cannot be changed.

That is, class is defined as final and avoids being inherited;

All of the member variables are private/final;

Cannot provide a method to change the class state (member variable) without the Set function of the member;

All methods cannot be overloaded;

Constructor do not refer to externally mutable objects, and if a class member is not a primitive variable or an immutable class, it must be defensive copy at initialization time to ensure that the class is immutable.

In the JDK, the string,the primitive wrapper classes, and the BigInteger and Big decimal are immutable classes.

As an example of string, if a class is immutable, the state of the created instance is immutable, but the class can have a way of changing the state, which is simply creating a new object.

String A1 = "A";

String A2 = "A"; Does not create a new object, both of which are the same instance. Immutable classes can cache instances for reuse and improve computational performance.

String B1 = new String ("A");//creation of an object

String B2 = new String ("A");//Create New OBJECT,B1 and B2 are different instance.

Another example of this would be to assign a value to a variable that contains an immutable object reference. Examples cite web sites:

Http://www.jb51.net/article/37889.htm

Tips: Strong non-volatile class: final class. Weakly immutable classes: all methods plus final

If a class member is not a primitive variable or an immutable class, it must be copied at the initialized life-practical depth to ensure that the class is immutable.

Java Immutable Class

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.