Application of final in Java

Source: Internet
Author: User
Final is not commonly used in Java, but it provides functions such as defining constants in C language, final also allows you to control whether your members, methods, or a class can be overwritten or inherited. These features enable final to play an indispensable role in Java, it is also one of the keywords that must be known and mastered when learning Java.
Final member
When you define a variable in a class and add the final keyword before it, this variable cannot be changed once initialized, the unchangeable meaning here is that its value is immutable for the basic type, and its reference for the object variable cannot be changed. It can be initialized in two places. One is its definition, that is, 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, not both at the time of definition, in the constructor, another value is given. The following code demonstrates this point:
Import java. util. List;
Import java. util. arraylist;
Import java. util. Collections list;
Public class bat {
Final Pi = 3.14; // address value when defined
Final int I; // The value cannot be given here because Initialization is required in the constructor.
Final list; // This variable is also the same as above
BAT (){
I = 100;
List = new vertex list ();
}
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 demonstrates the general usage of final. Here we use the initialization method in the constructor, which gives you a little flexibility. As shown in the two overloaded constructors of BAT, the first default constructor will provide you with the default value. The overloaded constructor will initialize the final variable based on the value or type you provided. However, sometimes you don't need this flexibility. You just need to set the value at the time of definition and never change. In this case, you don't need to use this method. There are two lines of statements commented out in the main method. If you remove the comment, the program will not be able to compile. This is to say, whether it is the value of I or the type of list, once initialized, it cannot be changed. However, B can specify the I value or list type through reinitialization. This is shown in the output:
I = 100 list type: Class java. util. Category list
I = 23 list type: Class java. util. arraylist
Another method is to define the final parameter in the method. For variables of the basic type, this method has no practical significance, because the variables of the basic type are passed values when calling the method, that is to say, you can change this parameter variable in the method without affecting the call statement. However, it is very practical for the object variable because the object variable is passed with its reference during transmission, in this way, your modification to the object variable in the method will also affect the object variable in the call statement. When you do not need to change the object variable used as the parameter in the method, use final to declare it, it will prevent you from accidentally modifying the call method.
In addition, when the internal class in the method uses the variable in the method, this parameter must be declared as final for use, 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
If you declare the method as final, it means that you already know that the function provided by this method has met your requirements and does not need to be extended, this method cannot be overwritten by any class inherited from this class, but inheritance can still inherit this method, that is, it can be used directly. In addition, there is a mechanism called inline, which enables you to directly Insert the method subject into the call when calling the final method, rather than performing routine method calls, such as saving breakpoints, this may improve the program efficiency. However, when your method subject is very large, or you call this method in multiple places, your calling subject code will expand rapidly, which may affect the efficiency. Therefore, use final for method definition with caution.
Final class
When using final on a class, you need to consider it carefully. Because a final class cannot be inherited by anyone, it means that this class is a leaf class in an inheritance tree, in addition, such designs have been considered perfect without modification or expansion. For members in the final class, you can define it as final or not final. For methods, because the class is final, they naturally become final. You can also explicitly add a final to the methods in the final class, but this is obviously meaningless.
The following program demonstrates the usage of the final method and 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 be inherited
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 final classes and common classes, but it loses its inherited features. The difference between the final method and the non-final method is also difficult to see from the program line, just remember to use it with caution.
Application of final in Design Mode
In the design pattern, there is a pattern called the immutable pattern. in Java, this pattern can be easily implemented through the final keyword. It explains the program bat used by final members. java is an example of the unchanged mode. If you are interested in this, you can refer to the explanation in the book "Java and mode" written by Dr. Yu Hong.
So far, the use of this, static, super and final has been completed. If you have been able to roughly express the differences and usage of these four keywords, it means that you have mastered it. However, nothing in the world is perfect. Java provides these four keywords, which brings great convenience to the programming of programmers, but it does not mean that you should use them everywhere, once an abused program is reached, it is counterproductive. Therefore, you must carefully consider it when using it.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.