The final keyword for Java

Source: Internet
Author: User

This article focuses on the use of Java final keyword-modified variables.
!!!! At the end of the article there are eggs!!!

1. Modifier class

When a class is decorated with final, it indicates that the class cannot be inherited. In other words, if a class you never let him inherit, you can use final to decorate. Member variables in the final class can be set to final as needed, but note that all member methods in the final class are implicitly specified as the final method.

When using the final modifier class, be careful to choose, unless the class is not intended to be inherited later or for security reasons, try not to design the class as the final class.

2. Modification methods

The following is part of the fourth edition of Java Programming thought, page 143th:
There are two reasons for using the final method. The first reason is to lock the method in case any inherited class modifies its meaning, and the second reason is efficiency. In earlier versions of Java implementations, the final method was converted to inline invocation. However, if the method is too large, you may not see any performance gains from inline calls. In the recent Java release, these optimizations do not need to be made using the final method. “
Therefore, the method is set to final only if you want to explicitly prohibit the method from being overwritten in the subclass.
Note: The private method of the class is implicitly specified as the final method.
Note: Above 1, 2 points from the analysis of the final keyword reference in Java

3. Modifier variables

1. Consider a String few final of the modified global variables in the reference class.
private final byte[] value; private final byte coder; private static final long serialVersionUID = -6849794470754667710L; static final boolean COMPACT_STRINGS;
It can be seen that only the serialVersionUID value (or instantiation) is assigned, and the following are substituted with two words.
Create a new class, under simulation:

For b , c you will be prompted with an error, "not yet initialized," but String the variables in the class do not have an error because:

    • StringAll constructor methods of a class are value assigned coder values ( direct or indirect )
      The direct or indirect explanations are as follows:

      The 2-parameter construction method does not give the b assignment directly, but it calls b another parameterless constructor for the assignment and does not give an error (it can also be assigned during class initialization b )
    • There must be and only one static code block assigned COMPACT_STRINGS , and multiple assignments will go wrong, such as:

2. Recall that final the modified variable is immutable?
The answer is yes, but it is immutable and can be further discussed.
Immutable can be explained simply as:

  • The basic type of the final modification can no longer be assigned;

    public class Demo {private final int b = 1;public void testInt(String[] args) {    b = 2;//很显然此处会报错}}
  • Final decorated objects and arrays, no longer point to new objects (arrays), but attributes (indexed values) can be changed;

    public class Demo {public void testObject() {    final User user = new User();    user.setName("111");//本行与下行不会报错,对象指向不能改变,但是属性可以改变    user.setName("222");    user = new User();//user不能 = new xx,也不能 = user02}public void testArray() {    final int[] array = new int[]{1,2,3,4,5,6};    array = new int[]{1,2,3,4,5,6};//报错    array[1] = 2;//正常}}class User{private String name;public String getName() {    return name;}public void setName(String name) {    this.name = name;}}
    3. final What else can you bring into the deep?
  • For compilers, the following chestnuts:

    public class Demo04 {public static void main(String[] args) {    String a = "a";    String b = "b";    String ab_add = a + b;    String ab_new = "ab";    System.out.println(ab_add == ab_new);//输出为 false    final String  c = "c";    String cd_add = c + "d";    String cd_new = "cd";    System.out.println(cd_add == cd_new);//输出为 true}}

    Why the above point is not an object, the following point is an object: Because the following c is final decorated, like constants, the "d" compiler as a constant, so
    String cd_new = "cd";The point is already there "cd" .

  • For virtual machines, the following chestnuts:

    public class Demo05 {static {    Demo05 demo05 = new Demo05();}Demo05() {    System.out.println("a = "+a+" b = "+b);}public static void main(String[] args) {}static int a = 123;static final int b = 456;}

    Analysis:
    1. In the normal class loading order, you should load static code and variables (in order), followed by member variables and construction methods.
    2. For the above code, after the static load, encountered the construction method of the class, resulting in the need to load the construction method (static related pause, after loading the secondary construction method, continue to load), at this time has a not been assigned the actual value, the temporary 0. So when the output is a 0.
    3. For b , the final output is not 0 because the modification causes the actual value to be assigned first.

    An interview with the String Class!

    Q: Did everyone know about the things you were final decorated with? ('? ') )?
    A: (?? .???) Oh, yes. But this is the reason, you listen to my explanation ~ this is not shameful!!
    Q: Oh? ('-ω??).
    A:. Balabala, in explanation
    Q: Is your value really not modifiable?
    A: Of course, unless ...(??_??)
    Q: Say it, unless what?(..??_??..)
    A:reflect .... Slipped away.~(/?Д?)
    Draw Wind mutation------> "code as follows":

      public class Demo04 {public static void main (string[] args) {String str = "1234";    Field field = GetField ("java.lang.String", "value"); Field.setaccessible (TRUE);//Do not write error: Demo04 cannot access a member of Class java.lang.String//(in module Java.base) with    Modifiers "private final" byte[] value = {};    try {value = (byte[]) field.get (str);    }catch (Exception e) {e.printstacktrace ();    } value[0] = ' a ';    Value[1] = ' B ';    System.out.println (str); The output is: ab34}/** * Description: Specify class name, specify property name, Get property * @param classname,fieldname * @return field */public static field GetField (S        Tring ClassName, String fieldName) {try {//Get class name Class C = Class.forName (ClassName);        Gets the class objects Object object = C.getconstructor (). newinstance ();        Gets the specified attribute field field = Object.getclass (). Getdeclaredfield (FieldName);    return field;    } catch (Exception e) {e.printstacktrace (); } return null;}}  
    At this point, this article concludes

    This article refers to:
    1.# Analysis of final keywords in Java
    2.# Java Virtual machine class loading mechanism--case study
    3.# Rookie Learn Java (15)--java reflection mechanism (II.)
    4.# yan text (? ′ω '?)

The final keyword for Java

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.