Depending on the context of the program, the Java keyword final has the meaning of "This cannot be changed" or "final state", which can be used to modify non-abstract classes, non-abstract class member methods, and variables. You may need to stop the change in two ways: design or efficiency.
- The final class cannot be inherited, there are no subclasses, and the methods in the final class are final by default.
- The final method cannot be overridden by a method of a class, but can be inherited.
- The final member variable represents a constant, which can only be assigned once, and the value will no longer change after the value is assigned.
- Final cannot be used to modify a construction method.
Note: The private member method of the parent class is not overridden by the class method, so the private type method defaults to the final type.
1. Final class
The final class cannot be inherited, so the member methods of the final class have no chance of being overwritten, and the default is final. In the design class, if the class does not need to have subclasses, the implementation details of the class are not allowed to change, and it is certain that the class will not be extended, then it is designed as the final class. In other words, for this or that reason, our class certainly does not need to make any changes, or for security reasons we do not want to subclass (subclass processing).
In addition, we may also consider the issue of the efficiency of implementation and want to ensure that all actions involving such objects are as effective as possible. As shown below:
Public classSmallbrain {} Public Final classDinosaur {inti = 7; intj = 1; Smallbrain x=NewSmallbrain (); voidf () {} @Override PublicString toString () {return"Dinosaur [i=" + i + ", j=" + j + ", x=" + x + "]"; } } Public classJurassic { Public Static voidMain (string[] args) {Dinosaur n=NewDinosaur (); N.F (); N.I= 40; N.J++; SYSTEM.OUT.PRINTLN (n); }}
Output results
Dinosaur [I=40, j=2, [email protected]]
View Code
Note: Data members can be either final or not, depending on our specific choices. The rules applied to final also apply to data members, regardless of whether the class is defined as final. after the class is defined as final, the result is simply a ban on inheritance-no more restrictions. However, because it prohibits inheritance, all methods in a final class default to final. Because they can no longer be overwritten at this time. So the compiler has the same efficiency option at this point as we explicitly declare a method as final.
2.final Method
If a class does not allow its subclasses to overwrite a method, you can declare this method as the final method. There are two reasons for using the final method:
First, lock the method to prevent any inherited classes from modifying its meaning and implementation.
Second, efficient. The compiler goes into an inline mechanism when it encounters a call to the final method, greatly improving execution efficiency.
For example:
Public class Finalmethod { publicvoid Nonfinalmethod () { System.out.println (" Nonfinalmethod "); } Public Final void Finalmethod () { System.out.println ("Finalmethod");} }
Public class extends finalmethod{ publicvoid Nonfinalmethod () { System.out.println ("test Nonfinalmethod "); } Public Static void Main (string[] args) { new Testfinalmethod (); T1.nonfinalmethod (); T1.finalmethod (); }}
Results:
Test Nonfinalmethodfinalmethod
View Code
3.final variable (constant)
A constant is represented by a final modified member variable, which cannot be changed once the value is given! There are three final modified variables: Static variables, instance variables, and local variables, representing three types of constants, respectively.
As you can see from the example below, once the initial value is given to the final variable, it cannot be changed.
In addition, when the final variable is defined, it can be declared without giving the initial value, which is also called the final blank, and in any case the compiler ensures that the blank final must be initialized before it is used. However, final whitespace provides greater flexibility in the use of the final keyword final, so that the final data members in a class can be implemented differently depending on the object, but with the same characteristics that remain constant.
Special Note: If the final decoration is a basic type, it means that the variable is given the value is immutable, that is, it is a constant, if the final decoration is an object, it means that the variable is given the reference is immutable, here to remind you that the What is immutable is only the reference that this variable holds, not the object that the reference points to. In the second case, final has the same meaning as in the first case. In fact, in the first two cases, there is a more appropriate description of the final meaning, that is, if a variable or method parameter is final decorated, it means that it can only be assigned once, but the Java Virtual machine set the default value of the variable is not recorded once assignment.
Packagecom.david.javaTest; Public classFinaltest {Private FinalString s = "final instance variable S"; Private Final intA = 100; Public Final intB = 90; Public Static Final intC = 80; Private Static Final intD = 70; Public Final intE//final blank, the initial value must be assigned when initializing the object PublicFinaltest (intx) {E=x; } /** * @paramargs*/ Public Static voidMain (string[] args) {NewFinaltest (2). F1 (2); Finaltest T=NewFinaltest (2); //decorating a variable with the final keyword means that the reference variable cannot be changed, and the contents of the object to which the reference variable is pointing can be modified. FinalStringBuffer StringBuffer =NewStringBuffer ("Hello StringBuffer"); System.out.println (StringBuffer); Stringbuffer.append ("Append"); System.out.println (StringBuffer); //t.a=101;//error, the value of the final variable cannot be changed once it is given//t.b=91;//error, the value of the final variable cannot be changed once it is given//t.c=81;//error, the value of the final variable cannot be changed once it is given//t.d=71;//error, the value of the final variable cannot be changed once it is givenSystem.out.println (T.A); System.out.println (T.B); System.out.println (T.C); //accessing static fields using object mode is not recommendedSystem.out.println (T.D);//accessing static fields using object mode is not recommendedSystem.out.println (FINALTEST.C); System.out.println (FINALTEST.D); //System.out.println (FINALTEST.E);//error because E is final and differs depending on the value of the object.System.out.println (T.E); Finaltest T1=NewFinaltest (3); System.out.println (t1. E); //final blank variable e differs depending on the object } Private voidTest () {System.out.println (NewFinaltest (1). A); System.out.println (FINALTEST.C); System.out.println (FINALTEST.D); } Public voidtest2 () {Final intA//final blank, assign value when needed Final intb = 4;//Local constants--final cases for local variables Final intC//final blank, has not been assigned.A = 3; //a=4, error, has been assigned value. //b=2, error, has been assigned value. } Public voidF1 (Final inti) {//i++;//I is the final type, and the value is not allowed to change.System.out.println (i); }}
4. Final Parameterswhen the function parameter is the final type, you can read it using the parameter, but you cannot change the value of the parameter.
Public Static void Main (string[] args) { new Test4 (). F1 (2); } Public void F1 (finalint i) { //i++; // I is the final type, and the value is not allowed to change. System.out.print (i); }}
5. The final modified variable must be initialized. There are several ways to initialize it:
- Initialized at the time of definition.
- The final variable can be initialized in the initialization block and cannot be initialized in a static initialization block.
- A static final variable can be initialized in a static initialization block and cannot be initialized in the initialization block.
- The final variable can also be initialized in the class's constructor, but the static final variable is not available.
Public classFinaltest {FinalString testring; Public Static FinalString Hello;//if it is not initialized in a static code block, the blank final field hello may not be been initialized Static{ FinalString Staticfinalvar = "Staticfinalvar"; Hello= "Hello have been initialized in static block"; //hello= "HH"; //testring = "This is initial block";//cannot make a static reference to the Non-static field testringSystem.out.println (Staticfinalvar); System.out.println (hello); } {testring= "This is initial block"; System.out.println (testring); } Public Static voidMain (string[] args) {NewFinaltest (2); }}
6. Face Questions
When you use the final keyword to decorate a variable, is the reference immutable or does the referenced object not change?
When you use the final keyword to decorate a variable, it means that the reference variable cannot be changed, and the contents of the object to which the reference variable is pointing can be changed . For example, for the following statement:final stringbuffer a=new stringbuffer ("immutable"), execution of thefollowing statement will report a compile-time error: a= New StringBuffer (""); However, the following statement can be executed by compiling: A.append (
Java Keyword final