Variable classes and immutable classes (1)

Source: Internet
Author: User

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
 

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.