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