Detailed description of final keywords in Java

Source: Internet
Author: User
This article mainly introduces the final keyword. through the basic usage of the final keyword and the understanding of the final keyword, if you need it, you can refer to the final keyword. many people may be familiar with it, the final keyword may be frequently used when anonymous internal classes are used. In addition, the String class in Java is a final class, so today we will learn about the usage of the final keyword.
I. basic usage of final keywords. 2. in-depth understanding of final keywords

I. basic usage of final keywords

In Java, final keywords can be used to modify classes, methods, and variables (including member variables and local variables ). The following describes the basic usage of the final keyword from these three aspects.

  1. modifier class

When a class is modified with final, it indicates that the class cannot be inherited. That is to say, if you never let a class be inherited, you can use final to modify it. The member variables in the final class can be set as final as needed, but note that all member methods in the final class are implicitly specified as final methods.

When using final to modify a class, be careful when selecting it. unless the class is not inherited in the future or for security reasons, try not to design the class as a final class.

2. modification method

The following passage is taken from page 143rd of the fourth edition of Java programming ideology:

"There are two reasons for using the final method. The first reason is to lock the method to prevent any inheritance class from modifying its meaning. The second reason is efficiency. In earlier Java implementations, the final method is converted into an embedded call. However, if the method is too large, you may not be able to see any performance improvement caused by embedded calls. In the latest Java version, the final method is not required for these optimizations. "

Therefore, if you want to explicitly prohibit this method from being overwritten in the subclass, set the method to final.

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

  3. modify variables

Modifying variables is the most widely used part of final, and is also the focus of this article. First, let's take a look at the basic syntax of final variables:

For a final variable, if it is a basic data type variable, its value cannot be changed once it is initialized; if it is a reference type variable, after initialization, you cannot point it to another object.

For example:

  

In the above code, an error is reported for the re-assignment of the variables I and obj.

2. in-depth understanding of final keywords

After learning about the basic usage of the final keyword, let's take a look at the obfuscation of the final keyword.

1. what is the difference between the final variable of the class and the common variable?

When final is used to act on the member variables of the class, the member variables (note that it is the member variables of the class, and the local variables only need to be initialized and assigned values before use) the value must be initialized at the time of definition or in the constructor. once the final variable is initialized and assigned a value, it cannot be assigned again.

  So what is the difference between final variables and common variables? The following is an 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));  }}

True
False

You can first think about the output result of this question. Why is the first comparison result true, and the second comparison result fasle.

The difference between final variables and common variables is that when final variables are of the basic data type and String type, if the exact value of final variables can be known during compilation, the compiler uses it as a constant during the compilation period. That is to say, where the final variable is used, it is equivalent to directly accessing this constant and does not need to be determined at runtime. This is a bit like macro replacement in c.

Therefore, in the above code, because variable B is modified by final, it will be treated as a compiler constant, so where B is used, it will directly replace variable B with its value. The access to variable d needs to be done through the link at runtime.

We should understand the differences, but note that the compiler will perform such optimization only when the final variable value is accurately known during compilation, for example, the following code won't be 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 result of this code is false..

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

As mentioned above, reference variables modified by final cannot point to other objects once they are initialized and assigned values. is the content of the object pointed to by the referenced variable? Let's look at the example below:

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 compiled smoothly and has output results. The output result is 1. This indicates that after the referenced variable is modified by final, although it cannot point to another object, the content of the object it points to is variable.

3. final and static

In many cases, it is easy to confuse static and final keywords. static acts on member variables to indicate that only one copy is saved, while final is used to ensure variable immutability. Let's look at the example below:

public class Test {  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();}

Run this code and you will find that the two j values printed each time are the same, while the I values are different. Here we can know the difference between final and static variables.

4. Why can only external local variables used in anonymous internal classes be final variables?

For this question, please refer to the explanation in "Java internal class explanation" in the previous blog, and I will not go into details here.

5. Questions about final parameters

"When you do not need to change the object variable as a parameter in the method, use final to declare it, it will prevent you from accidentally modifying the variables outside the call method. "I personally understand that this is inappropriate.

Because no matter whether the parameter is a variable of the basic data type or a variable of the reference type, using final declaration will not achieve the effect described above.

Let's see this example:

The above code seems to make people think that after final modification, they cannot change the value of variable I in the method. As you may not know, the variable I in the changeValue and main methods is not a variable at all, because the java parameter passing adopts value passing. for the basic type variables, it is equivalent to directly copying the variables. Therefore, without final modification, changing the value of variable I inside the method will not affect the I outside the method.

Let's look at the following code:

public class Test {  public static void main(String[] args) {    MyClass myClass = new MyClass();    StringBuffer buffer = new StringBuffer("hello");    myClass.changeValue(buffer);    System.out.println(buffer.toString());  }}class MyClass {  void changeValue(final StringBuffer buffer) {    buffer.append("world");  }}

Run this code and you will find that the output result is helloworld. Obviously, modification with final does not prevent changing the content of the object pointed to by the buffer in changeValue.

Some people say that if final is removed, what should we do if buffer points to other objects in changeValue. If you have such an idea, you can write the code and try out what the result is. if you remove final and then point the buffer to another object in changeValue, it does not affect the buffer in the main method. The reason is that java uses value transfer. For referenced variables, it passes the referenced value, that is, the real parameter and the form parameter are directed to the same object at the same time, therefore, it does not affect the real parameter to direct the form parameter to another object.

The above is a detailed description of the final keywords in Java, and I hope to help you.

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.