There are three uses for final in Java: Final member variable when you define a variable in a class, precede it with the final keyword, that is, the variable is immutable once it is initialized, and the immutable meaning here is the value immutable for the base type,
For an object variable, the reference cannot be changed, but the contents of the object to which the reference variable is directed can still be changed. Its initialization can be in three places, one is its definition, that is, the final variable is defined directly to its value, and the second is in the constructor.
And before Java1.1, only the value can be given at the time of definition.
Three is at the beginning of the code block {} or static{} The following code demonstrates this: more detailed discussion please refer to the initialization of final variable import java.util.List;
Import java.util.ArrayList;
Import java.util.LinkedList; public class Bat {final double PI = 3.14//////////////////////////////////////////////////= Final list L cannot be given here. Ist
This variable is also the same as the above Bat () {i = 100;
List = new LinkedList ();
} Bat (int II, List l) {i = II;
list = L;
public static void Main (string[] args) {bat b = new Bat (); B.list.add (New Bat ()); The reference is immutable, but the reference to the content is variable//b.i=25; Syntax error I is the immutable//b.list=new ArrayList ();
Error, object reference is immutable System.out.println ("i=" + b.i + "List Type:" + b.list.getclass ());
b = New Bat (new ArrayList ()); B.list.add (New Bat());
System.out.println ("i=" + b.i + "List Type:" + b.list.getclass ());
Again for example, for the following statement: Final StringBuffer a=new stringbuffer ("immutable");
Execute the following statement to report compile-time errors: A=new StringBuffer ("");
However, the following statements can be executed by compiling: A.append ("broken!"); When you define a parameter for a method, you might want to block the parameter object that is passed in by the method's internal modification: public void methods (final stringbuffer param) {} In fact, this is not possible, and the following code can still be added inside the method
To modify the parameter objects, as well as other objects: Param.append ("a");
Looking at an example//: Finaldata.java//the Effect of final on fields class Value {int i = 1;}
public class FinalData {//Can is Compile-time constants Final int i1 = 9;
static final int I2 = 99;
Typical public constant:public static final int I3 = 39;
cannot be compile-time constants:final int i4 = (int) (Math.random () * 20);
static final int i5 = (int) (Math.random () * 20);
Value V1 = new value ();
Final Value v2 = new value ();
Static final Value v3 = new value (); // ! Final Value v4; Pre-java 1.1 Error:for No initializer
Arrays:final int[] A = {1, 2, 3, 4, 5, 6};
public void print (String id) {System.out.println (id + ":" + "I4 =" + I4 + ", i5 =" + i5);
public static void Main (string[] args) {FinalData fd1 = new FinalData (); // ! fd1.i1++; Error:can ' t change value, because I1 is final fd1.v2.i++; Object isn ' t constant! This can be because I in class Value is a normal variable fd1.v1 = new Value (); OK--not final for (int i = 0; i < fd1.a.length i++) fd1.a[i]++;
Object isn ' t constant! The following three make the same mistake Error:can ' t change handle//!
Fd1.v2 = new Value (); // ! Fd1.v3 = new Value (); //
// !
fd1.a = new Int[3];
Fd1.print ("Fd1");
SYSTEM.OUT.PRINTLN ("Creating new FinalData");
FinalData fd2 = new FinalData ();
Fd1.print ("Fd1");
Fd2.print ("Fd2"); The output result (because of the random function used above, the output may be different, but the rule is the same): Fd1:i4 = 4, i5 = 6 creating new FinalData Fd1:i4 = 4, i5 = 6 Fd2:i4 = ten, i5 = 6 knotsFruit Analysis: Fd1 and FD2 I4 found the value is always different, but the i5 value is the same, this is why.
We can see that the only difference between defining I4 and i5 is that the latter one is more static, and since final and static variables can be said to have only one data, their only difference is that the static variable belongs to the class and is a class variable, which is only loaded once.
Please refer to this article: Java_ the parent class and the subclass of the load principle and I4 although final, but it is still a common variable, belong to the instance variable, each create an object or will be loaded once, and because it is a random function, so the final result is different.
So: Be sure to distinguish between final and static final nuances.
When a variable is decorated with the final keyword, the reference variable cannot be changed, and the contents of the object to which the reference variable is directed can be changed. This program is a simple demonstration of final general usage. This gives you a little flexibility by using the method of initializing in a constructor here. As shown in the two overloaded constructors of bat, the first default constructor gives you the default value, and the overloaded constructor initializes the final variable based on the value or type you provide. But sometimes you don't need this flexibility, you just need to define the value and never change it, then don't use this method. In the main method, there are two lines of comment out, if you remove the annotation, the program will not be compiled, which means that, whether it is the value of I or the type of list, once initialized, it can not be changed. However, B can be reinitialized to specify the value of I or the type of List, which is shown in the output: i=100 list type:class java.util.LinkedList i=23 list Type:class Java.util.ArrayList There is also a use to define that the parameters in the method are final, and for the basic type of variables, this does not make any sense because the variables of the base type are passed values when the method is invoked, That is, you can change the parameter variable in the method without affecting the calling statement, but it is useful for the object variable, because the object variable passes its reference when it is passed, so the modification of the object variable in the method also affects the object variable in the calling statement.
When you do not need to change an object variable as a parameter in a method, explicitly using final declaration will prevent you from inadvertently modifying the calling method. In addition, when the internal class in the method uses the parameter variable in the method, the parameter must also be declared final before it can be used, as shown in the following code: public class Inclass {void Innerclass (finalString str) {class IClass {IClass () {System.out.println (str);
} IClass IC = new IClass ();
public static void Main (string[] args) {Inclass inc = new Inclass ();
Inc.innerclass ("Hello");
The final method declares the method as final, that means you already know that this method provides functionality that satisfies your requirements, does not need to be extended, and does not allow any class inherited from this class to overwrite this method, but inheritance can still inherit this method, which means it can be used directly. There is also a mechanism called inline, it will allow you to insert the method body directly into the call place when you call the final method, instead of making routine method calls, such as saving breakpoints, pressing stacks, and so on, which may make your program more efficient, but when your method body is very large,
Or if you call this method in more than one place, your calling principal code expands rapidly and may affect efficiency, so be careful to use final method definitions.
All private methods in a class are final in a sense because they cannot be overridden elsewhere, and you can add the final modifier before a private method, but it doesn't make sense. Final class when you apply final to the class, you need to think about it, because a final class cannot be inherited by anyone, which means that this class is a leaf class in an inheritance tree, and that the design of this class has been considered perfect without any need for modification or extension. For a member variable in the final class, you can define it as final or not final. And for the method, because the class is final relationship, natural also become final type.
You can also explicitly add a final to the method in the final class, but this obviously doesn't make sense.
The following program shows the final method and final class usage: Final class Finals {final String str = "Final Data";
Public String str1 = "Non final data"; Final public VoiD print () {System.out.println ("final method.");
public void What () {System.out.println (str + "\ n" + str1); } public class Finaldemo {//extends final cannot inherit public static void Main (string[] args) {Finals f = new F
Inals ();
F.what ();
F.print (); As you can see from the program, the final class uses almost no difference to the normal class, except that it loses the inherited attribute.
The difference between final method and non final method is also difficult to see from the procedure line, just remember to use carefully. Note: Final application in design mode there is a pattern in design mode called invariant mode, in Java, through the final keyword can easily implement this pattern, in the final member of the program used in the Bat.java is an example of the invariant mode. If you are interested in this, you can refer to the "Java and Schema" book written by Dr. Shanhong.