1. final
Final can be used to modify classes, member methods, and member variables. It indicates final, unchangeable, and inherited:
The final class cannot be inherited. The method in the class is the final method by default, but the member variable in the class is not.
The final method cannot be overwritten by the quilt class. It can be understood as follows: the common method in JAVA is equal to the virtual method in C ++, and the final method in JAVA is equal to the common method in C ++.
The final Member indicates a constant. It can only be assigned once during declaration and cannot be assigned again later.
Public class Test {
Private final String S = "final instance variable ";
Private final int A = 10;
}
The final function parameter indicates that this parameter is a constant and cannot be changed in the function:
Public void f1 (final int I ){
I ++; // error: I is of the final type and cannot be changed.
System. out. print (I );
}
2. static
Static indicates Global static, which is used to modify member methods and member variables to form static code blocks:
The static method is similar to the static method of c ++. It can be used without creating a class instance. It cannot use the this and super keywords, and can only be a static member or static method in the category class.
Static member variables are similar to static members of C ++. They are shared with all class instances. Note that JAVA does not have local static variables.
Public class Main {
Static int I = 100;
}
Static code block is a code block that is executed only once when the JVM loads a class. It can be used to initialize static variables:
Public class Main {
Static int I = 100;
Static {
I = 30;
}
Public static void main (String [] args ){
// Here I should be 30
System. out. println (I );
}
}
3. Use final and static together
Global constants similar to C ++:
Static final int j = 200;