Home  >  Article  >  Java  >  Java language in-depth application of final in java

Java language in-depth application of final in java

黄舟
黄舟Original
2016-12-17 11:26:541228browse

Final is not commonly used in Java, but it provides us with functions such as defining constants in C language. Not only that, final also allows you to control whether your members, methods or a class can be overwritten or continued These features make final an indispensable position in Java, and it is also one of the key words that must be known and mastered when learning Java.
final member
When you define a variable in a class, add the final keyword in front of it. That means that once the variable is initialized, it cannot be changed. The meaning of unchangeable here is that its value cannot be changed for basic types. Change, but for object variables, their references cannot change again. Its initialization can be done in two places, one is at its definition, that is to say, it is assigned a value directly when the final variable is defined, and the other is in the constructor. You can only choose one of these two places, either give a value at the time of definition or give a value in the constructor. You cannot give a value at the time of definition and give another value in the constructor at the same time. The following code demonstrates this:
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class Bat{
final PI=3.14; //It is convenient when defining Give the address value
final int i; ;
                                                                 Bat b=new Bat();
b.list.add(new Bat());
//b.i=25;
//b.list=new ArrayList();
System.out.PRintln("I="+b. i+" List Type:"+b.list.getClass());
b=new Bat(23,new ArrayList());
b.list.add(new Bat());
System.out.println( "I="+b.i+" List Type:"+b.list.getClass());
}
}
This program simply demonstrates the regular usage of final. Using initialization in the constructor here gives you a little flexibility. As shown in Bat's two overloaded constructors, the first default constructor will provide you with a default value, and the overloaded constructor will initialize the final variable according to the value or type you provide. However, sometimes you don't need this flexibility. You just need to give its value when defining it and never change. In this case, don't use this method. There are two lines of statements in the main method that are commented out. If you remove the comments, the program will not compile. This means that whether it is the value of i or the type of list, once initialized, it cannot be changed. However, b can be reinitialized to specify the value of i or the type of list, as shown in the output:
I=100 List Type:class java.util.LinkedList
I=23 List Type:class java.util.ArrayList
Another usage is to define the parameters in the method as final. For variables of basic types, this has no practical significance, because variables of basic types are passed by value when calling the method, which means that you can Changing this parameter variable will not affect the calling statement. However, it is very practical for object variables, because the object variable is passed its reference when passing, so your modification of the object variable in the method will also affect the calling statement. For object variables, when you do not need to change the object variables as parameters in the method, explicitly using final to declare them will prevent your unintentional modifications from affecting the calling method.
In addition, when the inner class in the method uses the parameter variable in the method, the parameter variable must also be declared as final before it can be used, as shown in the following code:
public class INClass{
void innerClass(final String str){
class IClass{
IClass(){
}}} L iclass IC = New iClass ();
}
Public Static void Main (String [] ARGS) {
Inclass Inc = New Inclss ();
Inc.InnerClass ("Hello"); }
}
final method
Declaring the method as final means that you already know that the functions provided by this method have met your requirements and do not need to be extended, and any class that continues from this class is not allowed to override this method, but you can still continue. Continue this method, which means it can be used directly. There is also a mechanism called inline, which allows you to directly insert the method body into the calling point when calling the final method, instead of making routine method calls, such as saving breakpoints, pushing the stack, etc., which may cause problems. This will improve the efficiency of your program. However, when your method body is very large, or you call this method in multiple places, your calling body code will expand rapidly, which may affect efficiency, so you should use it with caution. final defines the method.
final class
When you use final for a class, you need to think carefully, because a final class cannot be continued by anyone, which means that this class is a leaf class in a continuation tree, and Designs of this type are considered perfect and do not require modification or extension. For members in final classes, you can define them as final or not. As for methods, since the class they belong to is final, they naturally become final. You can also explicitly add a final to the method in the final class, but this is obviously meaningless.
The following program demonstrates the usage of final methods and final classes:
final class final{
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 Continue
     public static void main(String[] args){
                                                                                                                                                                                                        final class There is almost no difference from the use of ordinary classes, except that it loses the characteristics of being continued. The difference between final methods and non-final methods is also difficult to see from the program line, just remember to use them with caution.
Application of final in design pattern
There is a pattern in design pattern called immutability pattern. This pattern can be easily implemented in Java through the final keyword. The program Bat.java used when explaining final members is one Example of immutable pattern. If you are interested in this, you can refer to the explanation in the book "Java and Patterns" written by Dr. Yan Hong.
 So far, the use of this, static, super and final has been explained. If you can roughly tell the difference and usage of these four key words, it means that you have basically mastered them. However, nothing in the world is perfect. Java provides these four keywords, which brings great convenience to programmers' programming, but it does not mean that you should use them everywhere. Once the program is abused, It's counterproductive, so please think carefully when using it.

The above is the in-depth application of Java language in java. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn