In Java, the final keyword can be used to decorate classes, methods, and variables (including member variables and local variables). Here's a look at the basic usage of the final keyword in three ways.
1. Modifier class
When a class is decorated with final, it indicates that the class cannot be inherited . Member variables in the final class can be set to all member methods in the Final,final class as needed and are implicitly specified as the final method.
2. Modification methods
The final-modified method cannot be overridden (multiple final-decorated methods can be overloaded). When the final decorated method in the parent class has access control permissions to private, the subclass cannot directly inherit to this method, where the same method name and parameters are defined in the subclass, and the new method is redefined for the subclass.
3. Modifier variables
1) The final modifier variable represents a constant, which can only be assigned once, and the value will no longer change after the value is assigned. If final modifies a reference type, the value refers to the value of the address and the content is mutable.
Public class Test06 { publicstaticvoid main (string[] args) { new Test06 (); Final New StringBuilder ("Hello"); Str.append ("World"); System.out.println (str);} }
The output result is HelloWorld.
2) When the final variable is the base data type and the string type, if you know its exact value during compilation , the compiler uses it as a compile-time constant.
You can know the exact value of it during compilation:
Public class Test06 { publicstaticvoid main (string[] args) { = " HelloWorld "; Final String b = "Hello"; = "Hello"; = B + "World"; = d + "World"; = = c)) ; = = e)); } }
The output is true,false; The compiler treats it as a constant, and a,c refers to "HelloWorld" in the constant pool.
The exact value of this is not known during compilation:
Public classTest06 { Public Static voidMain (string[] args) {String a= "HelloWorld"; FinalString B =Getword (); String D= "Hello"; String C= B + "World"; String e= d + "World"; System.out.println ((A==c)); System.out.println ((A==e)); } Public StaticString Getword () {return"Hello"; } }
The output result is false,false.
Final keyword in Java