In depth understanding the application of final in Java

Time:2020-2-13

Final is not commonly used in Java, but it provides us with functions such as defining constants in C language. Not only that, it 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 also a key word to know and grasp when learning Java One.

Final members

When you define a variable in a class, add the final keyword before it. That is to say, once the variable is initialized, it cannot be changed. The immutable meaning here is that its value is immutable for the basic type, and its reference is immutable for the object variable. Its initialization can be done in two places, one is at its definition, that is to say, when the final variable is defined, it is assigned directly, and the other is in the constructor. You can only choose one of these two places, either give a value when defining or give a value in the constructor. You cannot give a value when defining and 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; // address value is given when defining
Final int i; // because it is to be initialized in the constructor, no value can be given here
Final list list; // this variable is the same as 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());
//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 is a simple demonstration of the general use of final. Use the initialization method in the constructor here, which gives you a little flexibility. As shown in bat’s two overloaded constructors, the first will provide you with the default value, and the overloaded constructor will initialize the final variable according to the value or type you provide. Sometimes, however, you don’t need this flexibility. You just need to define the value and never change it. Don’t use this method. In the main method, two lines of statements are commented out. If you remove the comments, the program cannot be compiled. That is to say, no matter the value of I or the type of list, once initialized, it cannot be changed. However, B can specify the value of I or the type of list by reinitializing, which is shown in the output:


I=100 List Type:class java.util.LinkedList
I=23 List Type:class java.util.ArrayList

Another way is to define the parameters in a method as final. For variables of basic type, it has no practical significance. Because variables of basic type pass values when calling a method, that is to say, you can change this parameter variable in a method without affecting the call statement. However, for object variables, it is very practical, because object variables pass values When delivering, it is to pass its reference, so your modification of the object variable in the method will also affect the object variable in the call statement. When you don’t need to change the object variable as a parameter in the method, you can explicitly use final for declaration, which will prevent your unintentional modification from affecting the call method.

In addition, when the internal class in the method uses the parameter variable in the method, the parameter variable must also be declared final to be used, as shown in the following code:


public class INClass{
void innerClass(final String 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");
}
}

Final method

Declare the method as final, which means that you know that the function provided by this method has met your requirements, and you do not need to extend it, and you do not allow any class continuing from this class to overwrite this method, but you can still continue this method, that is, you can use it directly. In addition, there is a mechanism called inline, which enables you to directly insert the method body into the calling function when you call the final method, instead of making routine method calls, such as saving breakpoints, pressing stacks, etc., which may improve your program efficiency. However, when your method body is very large, or you call this method in multiple places, then your calling body The code will expand rapidly, which may affect the efficiency, so you should be careful with final method definition.

Class final

When you use final on a class, you need to think about it carefully, because a final class cannot be continued by anyone, which means that this class is a leaf class in a continuation tree, and the design of this class has been considered perfect without modification or expansion. For members in the final class, you can define them as final or not final. As for methods, because of the relationship between the class and final, they naturally become final. You can also explicitly add a final to the method in the final class, but this obviously doesn’t make sense.

The following program demonstrates the use of the final method and the final class:

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 f=new final();
f.what();
f.print();
}
}

It can be seen from the program that there is almost no difference between the use of the final class and the ordinary class, but it has lost the feature of being continued. The difference between the final method and the non final method is also hard to see from the program line, just remember to use it carefully.

Application of final in design pattern

In the design pattern, there is a pattern called immutable pattern, which can be easily implemented in Java through the final keyword. The program bat.java used in explaining the final members is an 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 finished. If you can roughly say the difference and usage of these four key words, it means that you have basically grasped them. However, everything in the world is not perfect. Java provides these four key words, which brings great convenience to the programmer’s programming, but it does not mean that you should use them everywhere. Once the abuse of the program is achieved, it will backfire, so you must carefully consider when using them.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

Building grpc service with golang

This tutorial provides a basic tutorial for go to use grpc In the tutorial you will learn how to: stay.protoA service is defined in the file. Use the protocol buffer compiler to generate client and server code. Use grpc’s go API to write a client and server for your service. Before you continue, make sure […]