One. Final
Meaning: Adj. final, Final; The decisive; Non-changing. In Java is a reserved keyword that can declare member variables, methods, classes, and local variables. Once you have the reference declaration as final, you will not be able to change the reference, the compiler will check the code, and if you attempt to initialize the variable again, the compiler will report a compilation error.
1) modify member variables, local variables : When writing a program, we often need to explain that a data is immutable, and we become constants. In Java, a variable modified with the final keyword can only be assigned once, and its value cannot be changed during the lifetime. More importantly, final will tell the compiler that this data will not be modified, so the compiler may be able to replace the data or even perform calculations at compile time, which can optimize our program. It is a bit different for reference types and basic types.
Class value{ private int i; Public value () { } public value (int i) { this.i = i; } public int Geti () { return i; } public void SetI (int i) { this.i = i; } } public void Finaltest () { //Basic data type final int A; A = 1; a = 2; Compile alert error final value value = new value (2); VALUE.I = 3;//Change the property value of the object, compile without error // value = new value (4);//new object, compile error
The value of a variable cannot be changed when final modification of the base data type; When the final modifier refers to a type, the address of the object referenced by the variable can not be changed (point to the object only and no longer point to other objects), but the referenced object can be changed.
2) Modification method : The method is preceded by the final keyword, which means that the method cannot be overridden by a quilt class. If you think that the functionality of a method is complete enough, and you don't need to change it in a subclass, you can declare that this method is final.
Class value{public final int test () { return 1; } } Class Subvalue extends value{ // @Override //public final int test () {//compilation error:override Method is final // return 2; // }
3) Modification method parameter : The formal parameter of the method uses the final modification, which means that the parameter cannot be modified in this method (the underlying data type cannot be modified, and the reference type cannot modify the address of the referencing object).
public void fianlParams1 (final int i) { // i = 3;//compilation Error:can not assign a value to final variable "I " } public void FianlParams2 (final Value i) { // i = new Value (n);//compilation Error:can not assign A value to final variable "I" }
4) modifier class : A class that uses final to decorate is called the final class. The final class is generally functionally complete and cannot be inherited. There are many classes in Java that are final, such as String, Interger, and other wrapper classes.
Java Basics: Keyword final,static