Home > Java > JavaBase > java mutable classes and immutable classes

java mutable classes and immutable classes

angryTom
Release: 2019-11-14 09:54:35
Original
2120 people have browsed it

java mutable classes and immutable classes

java mutable classes and immutable classes

a) Mutable classes

After obtaining an instance of this class, you can change the content of this instance, such as changing the internal member variables of this instance.

b) Immutable class

After obtaining an instance of the class, the content of this instance cannot be changed. Once an immutable instance is created, the value of its internal member variables It can no longer change.

Immutable classes are typically like String. Once a String object is created, it cannot be changed. We change the value of the String object in the foreground. In fact, a new String object is created in the memory, and the original object remains unchanged. Change.

StringBuild is a mutable class, because every modification to its object affects the object itself and does not create a new object.

Characteristics of immutable classes:

All members are private final

Does not provide methods to change members, member variable assignment is generally done in the construction Assign a value in a function.

Ensure that all methods will not be overloaded: use final to define the class, or add final to all methods of the class.

If a class member is not a primitive variable or an immutable class, it must Ensure the immutability of the class by using the deep clone method during member initialization or get method.

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of java mutable classes and immutable classes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template