Final usage in Java

Source: Internet
Author: User

Final is not used in Java, but it provides us with functions such as defining constants in C, and final allows you to control your members, your methods, or whether a class can be overwritten or inherited. These characteristics make final in Java has an indispensable position, but also learn Java must know and master one of the keywords.

Final member
When you define a variable in a class, precede it with the final keyword, that is, once the variable is initialized, it cannot be changed, and the immutable meaning here is immutable for the base type, and the reference to the object variable cannot be changed. Its initialization can be in two places, one is its definition, that is, the final variable is defined directly to its value, and the second is in the constructor. These two places can only be selected, either by giving values at the time of definition, or by giving values in the constructor, not both at the time the value is defined, and by giving another value in the constructor. This is illustrated by the following code:
Import java.util.List;  Import java.util.ArrayList;  Import java.util.LinkedList; The public class bat{final pi=3.14///////////When defined, the final int i;//because it is initialized in the constructor, it is no longer necessary to give the value to the end list List;//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 ());  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 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 result:
i=100 List Type:class java.util.LinkedList
i=23 List Type:class java.util.ArrayList
Another use is to define that the parameters in the method are final, for a variable of the base type, this does not make any sense, because a variable of the base type is passed as a value when the method is invoked, which means that you can change the parameter variable in the method without affecting the calling statement, but it is useful for object variables. , because the object variable passes its reference when it is passed, so your modification of the object variable in the method also affects the object variable in the calling statement, and when you do not need to change the object variable as a parameter in the method, the explicit use of final declaration will prevent you from inadvertently modifying the calling method.
In addition, when an inner class in a method uses a parameter variable in a method, the parameter must also be declared final before it can 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
Declaring a method final means that you already know that the 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.

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 of 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 demonstrates the final method and the final class usage:
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);  The public class Finaldemo {//extends final cannot inherit public static void Main (string[] args) {final f=new final ();  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.
The application of final in design pattern
In design mode, there is a pattern called invariant mode, in Java through the final keyword can easily implement this pattern, in the final member of the application of the program 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.

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.