A, final keyword
1.1 Definitions
final keyword is used to modify the amount of change is no longer occurring, it can be used to modify classes, attributes, methods, local variables.
1.2
Modified class : final modified class represents the class can not be inherited, indicating that the class has been very perfect, very difficult to come to the classes be expanded.
Typical applications: String, StringBuffer, System
Modifying attributes : final modified attribute indicates the attribute can not be changed once it is initialized, the final modification of the properties of the object to be completed before the initialization is completed, the position of a display can initialize initialization, the initialization code block, the constructor initializes
Example:
class Person {
final int age = 10; //显示初始化
final String name;
final String sex;
{
name = "xiao ming"; //代码块初始化
}
public Person() {
sex = "男"; //构造变量初始化
}
}
Modification methods : final modification methods shows that the method can not be overridden by subclasses, with a typical use getClass Object class () method.
Modified local variables : the basic data types, and may be modified reference data types, data types represented in the modified base value can not be modified, the modified reference data type of the variable that it can not modify the address value, i.e., point.
Second, a set of domain security
2.1 Definitions
Ensure the immutable elements of the collection is the regional security.
In the above-mentioned mentioned final modified reference data types of variables, indicates that it can not point to a new object, the same applies for the array, however, we use an array, you may not just want to make sure not to change the reference to the array, but also do not want to change the contents of the array, this final is not.
Example:
public class FinalTest {
private static void output(final List<Integer> arrayList) {
for(int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + " ");
arrayList.set(i, arrayList.get(i) + 1); //对 arrayList 中的元素更改
}
}
public static void main(String[] args) {
final List<Integer> arrayList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); //定义 final 类型的 List
output(arrayList);
System.out.println();
output(arrayList);
}
}
/*结果:
1 2 3 4 5
2 3 4 5 6
*/
2.2
To ensure the security domain, can be used in the C language const keyword in java, need to use immutable classes to the collection packaging:
public static void main(String[] args) {
final List<Integer> arrayList = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)));
output(arrayList);
System.out.println();
output(arrayList);
}
/*结果:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.set(Collections.java:1311)
at static_final.FinalTest.output(FinalTest.java:9)
at static_final.FinalTest.main(FinalTest.java:15)
*/