There are three ways to use final in Java

Source: Internet
Author: User

Final member variable

When you define a variable in a class, precede it with the final keyword, that is, once the variable is initialized, it is immutable, the immutable meaning is immutable for the base type, and the reference to the object variable is immutable, but the contents of the object that the reference variable points to can be changed.


Its initialization can be in three places,

The first is its definition, which means that it is assigned a value directly when the final variable is defined.

The second is in the constructor. And before Java1.1, you can only give a value when you define it.

Third, in the beginning of the code block {} or static{}

The following code demonstrates this: For a more detailed discussion, please refer to the discussion on initialization of final variables

Import java.util.list;import java.util.arraylist;import java.util.linkedlist;public class  Bat {    final double PI = 3.14; //  address values when defined     final int i; //  because you want to initialize in the constructor, you can't give the value again here      final list list; //  This variable is also 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 ();   &nbsP;     b.list.add (New bat ()); The reference is immutable, but the reference points to the content that can be changed         // b.i=25;   syntax  error  i is immutable         //b.list=new arraylist (); Error, the object reference is immutable         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 ());     } again, for example,  For the following statement: Final stringbuffer a=new stringbuffer ("immutable");  Executing the following statement will report a compile-time error: A=new stringbuffer (""); However, the following statements can be executed by compiling: A.append (" broken!");   When someone defines a method's parameters, it may want to use the following form toBlock method Internal modification of incoming parameter objects: Public void method (Final  stringbuffer  param) {} In fact, this is impossible, Inside this method, you can still add the following code to modify the Parameter object, as well as other objects:   param.append ("a"); In an example//: finaldata.java//the effect  of final on fieldsclass value {    int i = 1 ;} public class finaldata {    // can be 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) &NBSP;{&NBSp;       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");     }} Output (due to the use of random functions above, so the output may be different, but the law is the same):fd1: i4 = 4, i5 = 6creating new  finaldatafd1: i4 = 4, i5 = 6fd2: i4 = 10, i5 =  6 Results Analysis: FD1 and fd2 The I4 found value is always different, but the value of i5 is the same, this is why? We can find that the only difference between the definition of I4 and i5 is that the latter has a static, because the final and static variables can be said to have only one data, their only difference is that the static variable belongs to the class, is a class variable, will only be loaded once. Please refer to this article: Java_ the loading principle of parent class and subclass I4 although it is final, it is still an ordinary variable, it is an instance variable, each object created will be loaded once, and because it is a random function, the final result is different. So: Be sure to differentiate between final and sThe nuances of tatic final. When you use the final keyword to decorate a variable, it means that the reference variable cannot be changed, and the contents of the object to which the reference variable is pointing can be changed. This program is a simple demonstration of the general use of final. Here you have a bit of flexibility by using methods that are initialized in the constructor. As shown in the two overloaded constructors for bat, the first default constructor gives you the default value, and the overloaded constructor initializes the final variable based on the value or type that you provide. However, sometimes you don't need this flexibility, you just need to give it a value when you define it and never change it. There are two lines in the main method commented out, if you remove the comment, the program will not be compiled, this is to say, regardless of the value of I or the type of list, once initialized, 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.linkedlisti=23  List Type:class  Java.util.ArrayList There is also a use of the definition method of the parameter is final, for the basic type of variable, this does not have any practical significance, because the basic type of the variable is called when the method is a value, that is, you can change the parameter in the method of the argument variable without affecting the call statement, but the object is changed Volume, but it is very useful, because the object variable is passed its reference, so you modify the object variable in the method will also affect the object variable in the call statement, when you do not need to change the parameters of the object variable in the method, the explicit use of final declaration, will prevent you unintentional modification and affect the calling method. In addition, when an inner class in a method is used with a parameter variable in a method, this parameter must also be declared final to be used, as shown in the following code:public class inclass {     Void innerclass (FINAL&NBSP;STRING&NBSP;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 final, which means that you already know that the functionality provided by this method has met your requirements, does not need to be extended, and does not allow any class inheriting from this class to overwrite the method, but inheritance can still inherit this method, which means that it can be used directly. There is also a mechanism called inline, which allows you to insert the method body directly into the call when you call the final method, instead of making routine method calls, such as saving breakpoints, pressing stacks, and so on, which may improve your program efficiency, but when your method body is very large, Or you call this method in many places, then your calling body code will quickly expand, it may affect efficiency, so you should be careful to use final method definition. All private methods in a class are final in a sense, because they cannot be overwritten elsewhere, and you can add the final modifier before a private method, but it doesn't make sense. Final class when you use the finalOn a class, you need to think carefully, because a final class cannot be inherited by anyone, which means that the class is a leaf class in an inheritance tree, and that the design of such a class is considered perfect without modification or extension. For a member variable in the final class, you can either define it as final or not final. And for the method, because the class is the final relationship, Nature will become final type. You can also explicitly add a final to the method in the final class, but this is obviously meaningless. The following procedure demonstrates the use of the final method and the final class: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)  {    &Nbsp;   finals f = new finals ();         f.what ();         f.print ();     } It can be seen from the program that There is almost no difference between the final class and the normal class, except that it loses the inherited attribute. The difference between final and non-final methods is difficult to see from the program line, just remember to use caution. Note: Final application in design mode there is a pattern in design mode called invariant mode, which can be easily implemented in Java by the final keyword, and the program Bat.java used to explain the final member is an example of the invariant pattern. If you're interested, you can refer to the book "Java and Patterns" written by Dr. Shanhong.


There are three ways to use final in Java

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.