Java Final keyword

Source: Internet
Author: User
Tags modifier

2017-11-05 15:08:47

    • Final keyword

The Java keyword final has the meaning of "This cannot be changed" or "final state", which can be used to modify non-abstract classes, non-abstract class member methods, and variables.

There are two reasons to use 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. --java Programming Ideas

The effect of the final modifier:

    1. The final class cannot be inherited, there are no subclasses, and the methods in the final class are final by default.
    2. The final method cannot be overridden by a method of a class, but can be inherited.
    3. The final member variable represents a constant, which can only be assigned once, and the value will no longer change after the value is assigned.
    4. Final cannot be used to modify a construction method.
    5. Used to modify a method parameter to indicate that its value cannot be changed during the lifetime of a variable.

Note : The private method of the class is implicitly specified as the final method.

Final variables are stored in the constant pool in the method area

~ Final class:

The final class cannot be inherited, so the member methods of the final class have no chance of being overwritten, and the default is final. In the design class, if the class does not need to have subclasses, the implementation details of the class are not allowed to change, and it is certain that the class will not be extended, then it is designed as the final class.

~ Final method:

If a class does not allow its subclasses to overwrite a method, you can declare this method as the final method.
There are two reasons for using the final method:
First, lock the method to prevent any inherited classes from modifying its meaning and implementation.
Second, efficient. The compiler goes into an inline mechanism when it encounters a call to the final method, greatly improving execution efficiency.

~ final variable (constant):

A constant is represented by a final modified member variable, which cannot be changed once the value is given!
There are three final modified variables: Static variables, instance variables, and local variables, representing three types of constants, respectively.
In addition, when the final variable is defined, it can be declared without giving the initial value, which is also called the final blank, and in any case the compiler ensures that the blank final must be initialized before it is used. However, final whitespace provides greater flexibility in the use of the final keyword final, so that the final data members in a class can be implemented differently depending on the object, but with the same characteristics that remain constant.

~ Final parameter:

When the function parameter is the final type, you can read it using the parameter, but you cannot change the value of the parameter.

Second, in-depth understanding of the final keyword

~ The difference between the final variable and the normal variable

When you use final action on a member variable of a class, the member variable (note is the member variable of the class, the local variable needs to be guaranteed to be initialized before use) must be assigned in the definition or constructor, and once the final variable is initialized, it can no longer be assigned a value.

        String a = "Hello2";        String t = "Hello2";        Final String b = "Hello";        String d = "Hello";        String C = b + 2;        String E = d + 2;        String f = "Hello" + 2;        System.out.println (e);        System.out.println ((A = = c));  True        System.out.println ((a = = e));  False        System.out.println ((a = = t));  True        System.out.println ((a = = f));  True

Let's start by explaining why the second is false and the third one is true.

In fact, these two are very simple, the second is false because Java in the bottom is actually called the new StringBuilder () operation, so that the operation is not directly from the constant pool to fetch the address of the data, so naturally finally compare the address of the time is not the same.

The third is true because both of the address values are the address values in the constant pool and are therefore the same.

So why is the first one also true?

This is the difference between the final variable and the normal variable, when the final variable is the base data type and the string type, if you can know its exact value during compilation, the compiler will use it as a compile-time constant. That is, where the final variable is used, it is equivalent to the constant that is accessed directly, and does not need to be determined at run time. This is a bit like a macro substitution in C language. So in the preceding section of code, because the variable B is final decorated, it is treated as a compiler constant, so where B is used, the variable b is replaced directly with its value.

In fact this is the same as the final F, here is the result of doing a compiler optimization operation.

The compiler does this only if the final variable value is known exactly during compilation, such as the following code is not optimized:

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 code is false. one thing to note here is this: don't assume that some data is final and you know its value at compile time, and with variable b we know that it's initialized with the Gethello () method, and he's going to know its value at run time.

~ is the content of the object pointed to by the final modified reference variable variable?

In the above mentioned the final modified reference variable once the initialization of the assignment can no longer point to other objects, then the reference variable point to the contents of the object 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;}

This code can be successfully compiled and has output results, the output is 1. This means that after the reference variable is final decorated, it cannot point to another object, but the contents of the object it points to are mutable.

~ Final parameter

In practice, we can modify a member variable, a member method, a class, or a parameter, if a parameter is final, in addition to the final modifier, which means the parameter is immutable. If we modify this parameter in the method, the compiler will prompt you: The final local variable I cannot be assigned. It must is blank and not using a compound assignment. Look at the following example:

public class Testfinal {public        static void Main (string[] args) {        testfinal testfinal = new testfinal ();        int i = 0;        Testfinal.changevalue (i);        System.out.println (i);            }        public void ChangeValue (final int i) {        //final parameter cannot be changed        //i++;        System.out.println (i);    }}

The value of the variable I cannot be changed in the method after the above code changevalue the parameter I in the method with the final decoration. It is worth noting that the method changevalue and the variable I in the Main method are not a variable at all, because the Java parameter pass takes the value pass, and for the basic type of variable, it is equivalent to copying the variable directly. So even without final modification, changing the value of the variable I within the method does not affect the I outside of the method.

Let's look at the following code:

public class Testfinal {public        static void Main (string[] args) {        testfinal testfinal = new testfinal ();        StringBuffer buffer = new StringBuffer ("Hello");        Testfinal.changevalue (buffer);        SYSTEM.OUT.PRINTLN (buffer);            }        public void ChangeValue (final stringbuffer buffer) {        //final modifies a parameter of a reference type and can no longer point it to another object, but the content to which it points is subject to change.        //buffer = new StringBuffer ("HI");        Buffer.append ("World");}    }

Running this code will reveal that the output is HelloWorld. It is clear that the final modification can no longer allow buffer to point to other objects, but the contents of the object to which buffer points are changed. Now suppose a situation, if final is removed, what will the result be? Look at the following code:

public class Testfinal {public        static void Main (string[] args) {        testfinal testfinal = new testfinal ();        StringBuffer buffer = new StringBuffer ("Hello");        Testfinal.changevalue (buffer);        SYSTEM.OUT.PRINTLN (buffer);            }        public void ChangeValue (StringBuffer buffer) {        //buffer re-points to another object,        buffer = new StringBuffer ("HI");        Buffer.append ("World");        SYSTEM.OUT.PRINTLN (buffer);}    }

Operation Result:

Hiworldhello

The result of the operation shows that when final is removed, the buffer points to other objects in ChangeValue, and does not affect the buffer in the main method, because Java takes a value pass, and for a reference variable, it passes the referenced value. This means that the argument and the parameter point to the same object at the same time, so having the parameter point back to another object has no effect on the argument.

In other words, a reference type is actually a weakening pointer, and the final qualified reference type's variable actually qualifies the pointer, but the value of the in-memory address pointed to by the pointer is self-altering.

  


Java Final keyword

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.