Java basics: 31st constant Member

Source: Internet
Author: User

When using a class to create an object, you need to assign values to each attribute so that a new object is generated.

Sometimes you want the property value of an object to not change after it is created, such as the ID card number. In this case, you need to set the property to a constant.

Constants are defined using final, for example:

Private final string ID;

The value of a constant cannot be changed. When can I assign a value to a constant?

There are two methods: assign values when defining them, and assign values through the constructor. The following two methods can be used:

Method 1:

Private final string id = "003 ";

Method 2:

Public consttest (string ID ){
This. ID = ID;
}

NOTE: If method 1 is used, you cannot assign a value to the constructor. The following code is incorrect:

Private final string id = "003 ";
Public consttest (string ID ){
This. ID = ID;
}

Constants must be assigned values in one of the preceding two ways. Otherwise, an error is returned.

Constants cannot be modified using other methods. The following code is also incorrect:

Public void setconsttest (){
Id = "002 ";
}

The difference between the two methods: In the first method, the attribute values of all objects in the class are the same. In this case, you can set the attribute values to static methods. Next time, we will introduce static methods. In the second method, each object has its own unchanged attribute values.

Last time: 30th object creation and accessNext time: 32nd talk about static membersLi xucheng csdn blog: Why? U= 124362 & C = 7be8ba2b6f3b6cc5

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.