Summary of the final keyword usage

Source: Internet
Author: User
Tags modifier
Directory

Basic usage of the final keyword of the catalog 1 modifier class 2 modifier 3 modifier variable in depth discussion of final and ordinary variables in final keyword 1 class 2 The object content of the final modified reference variable is variable 3final and static difference 4 explain why local and anonymous inner classes can only access local final variables

Final keyword I believe you will not be very strange, if you have used to define the internal class in the method, you must know that the inner class if you want to access the parameters in the method, the parameter requires a final declaration. Today's main system introduces the use of the final keyword. the basic usage of the final keyword

In Java, the final keyword can be used to decorate classes, methods, variables (including member variables and local variables). Now let's look at the final usage from these three aspects. 1. Cosmetic class

When final modifies a class, it indicates that the class cannot be inherited. The member variables in the final class can be final as needed, but all member methods in the final class are implicitly specified as final methods.
Note: When using the final modifier class, it is important to choose carefully, unless the class is not used for inheritance or for security reasons, try not to design the class as the final class. 2. Modification Method

"The main reason for using the final cosmetic method is to lock the method and prevent any inherited class from modifying its meaning." Therefore, the method is set to final only if you want to explicitly prohibit the method from being overwritten in a subclass.
Note: The private method of the class is implicitly specified as the final method. 3. Modifying variables

Modifying variables is the most widely used place in final use, and it is also the place to focus on understanding. Let's take a look at the basic syntax of final variables:
For a final variable, if it is a variable of the base data type, its value cannot be modified after it is initialized, and if it is a variable of a reference type, it cannot be directed to another object after it has been initialized.

Class man{
    private final int i = 0;
    Public Mans () {
       i = 1;//error
    final Object obj = new Object ();
    obj = new Object ();//Error
    }
}

In the code above, the redistribution of I and obj will be an error. in-depth discussion of final keywords

After understanding the basic usage of final, let's take a detailed look at where the final use is prone to error. 1, the final variable of the class and the difference between ordinary variables.

When you apply final to a member variable of a class, a member variable (note is a member variable, the local variable needs to be initialized before use) must be defined or assigned in the constructor, and the final variable can no longer be assigned once it has been initialized.
So what's the difference between the final variable and the ordinary variable? Look at the following example:

public class test{public
    static void Main (string[] args) {
        String a = "Hello2";
    Final String b = "Hello";
    String d = "Hello";
    String C = b + 2;
    String E = d + 2;
    System.out.println ((A = = c));
    System.out.println ((A = = e));
    }

Output: True False
Code Analysis:
As we all know that string is a final class, the final class is characterized by sharing data, = = is a comparison of addresses, and the final class string is the same, pointing to the same address. When an object is created with the literal value in "" in the String class, it is first found in the string pool space, and if there is a string address returned, no object is created in the string pool. If it is new to wear a string object in the heap space, there is no such procedure (string concatenation is the same, and each connection is equivalent to creating an object). So I'm looking at the output, why the first one is true, and the second is false. This is the difference between the final variable and the ordinary variable, and when the final variable is the base data type and the string type, the compiler will use it as a compile-time constant if it knows its exact value during compilation. That is, where the final variable is used, the equivalent of direct access to this constant is not required to be determined at run time. Because variable B is final decorated, it is treated as a compiler constant, so the variable B is replaced directly with its value where B is used. Access to variable D, however, needs to be done at run time through a link. Note, however, that the compiler does this only if you know exactly what the final variable value is during compilation, such as the following code will not be optimized:
Java code:

public class Test {public
    static void Main (string[] args)  {
        String a = "Hello2"; 
        Final String B = Gethello ();
        String C = b + 2; 
        System.out.println ((A = = c));
    }
    public static String Gethello () {return
        "Hello";
    }
}

The output of this piece of code is false. 2, the final modified reference variable to point to the content of the object is variable.

It is mentioned that the final-decorated reference variable cannot point to another object once the assignment has been initialized, so the content of the reference variable is variable. Look at the following example:

public class test{public
    static void Main (string[] args) {
        final MyClass MyClass = new MyClass ();
    System.out.println (++MYCLASS.I);
    }
Class myclass{public
    int i = 0;
}

The output result is 1. This means that after the reference variable is final decorated, it may not point to other objects, but the object content it points to is mutable. 3, final and static difference.

Static acts on a member variable (that is, a static variable) that has only one copy in memory (in order to conserve memory), the JVM allocates only one memory for the static variable, and completes the memory allocation of the static variable during the loading process, which can be accessed directly by the class name. And final is only to ensure that the variable is not changed, can not be changed is the reference point, the specific reference point to the value may be changed.

public class test00 {public
    static void Main (string[] args)  {
        MyClass myClass1 = new MyClass ();
        MyClass myClass2 = new MyClass ();
        System.out.println (myclass1.i);
        System.out.println (MYCLASS1.J);
        System.out.println (myclass2.i);
        System.out.println (MYCLASS2.J);
    }
Class MyClass {Public
    final double i = Math.random ();
    public static Double J = Math.random ();
}

The output shows that the J value of each print is the same, while the value of I is different. 4, explain why the local inner class and anonymous inner class can only access local final variables.

Believe this question everybody must have the doubt, below we will analyze slowly. As an example:

public class Test {public
    static void Main (string[] args)  {

    } public  
    void Test (final int b) {
        fi nal int a = ten;
        New Thread () {public
            void run () {
                System.out.println (a);
                System.out.println (b);
            };
        Start ();
    }
public class Test {public
    static void Main (string[] args)  {

    } public 
    void Test (final int a) {
        new Thr EAD () {public
            void run () {
                System.out.println (a);
            }
        }. Start ();
    }

We all know that after compiling, we will get two. class files, usually for Test.class and Test$1.class. Then, we analyze the process, and when the test method is finished, the life cycle of the variable A is over, and the thread object's life cycle may not be over, so it is impossible to continue accessing a in the thread's Run method, but in order to do so, Java uses the copy "means to solve it. The compiler replicates a local local variable by default during compilation. If the value of this variable is determined during compilation, the compiler defaults to add an equal literal to the constant pool of the anonymous inner class (local inner Class) or embeds the corresponding bytecode directly into the execution byte code. Therefore, the variable used in the anonymous inner class is another local variable, except that the value and the local variable in the method are equal. If the value of a local variable cannot be determined during compilation, the copy is initialized by the constructor argument. Therefore, in order to avoid inconsistency of data values, you must qualify the final type for the variable.

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.