A brief analysis of final keywords in Java

Source: Internet
Author: User
Tags modifier

A brief analysis of final keywords in Java

When it comes to the final keyword, it's probably a lot of people who are not unfamiliar with the final keyword when using anonymous internal classes. In addition, the string class in Java is a final class, so today we'll look at the use of the final keyword. The following is the directory outline for this article:

I. Basic usage of the final keyword

Two. In-depth understanding of final keywords

If there is any difference, please understand and welcome correct.

Please respect the author's labor results, reproduced please indicate the original link:

Http://www.cnblogs.com/dolphin0520/p/3736238.html

I. Basic usage of the final keyword

In Java, the final keyword can be used to decorate classes, methods, and variables (including member variables and local variables). Here's a look at the basic usage of the final keyword in three ways.

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.

3. Modifier variables

The modified variable is the most used place in final use, and it is also the focus of this article. First look at the basic syntax of the final variable:

  For a final variable, if it is a variable of the base data type, its value cannot be changed once initialized, and if it is a variable of a reference type, it cannot be pointed to another object after it has been initialized.

  As an example:

  

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

Two. In-depth understanding of final keywords

After understanding the basic usage of the final keyword, let's look at where the final keyword is easy to confuse.

1. What is the difference between a class's final variable and a 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.

So what is the difference between a final variable and a normal variable? Let's take a look at the following example:

1234567891011 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));    }}

  

Truefalse

We can first think about the output of this problem. Why the first comparison result is true, and the second compares the result to Fasle. 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. The access to variable D needs to be linked at run time. Presumably the difference should be understood, but note that the compiler does this only if the final variable value is known exactly during compilation, as the following code does not optimize:

12345678910111213 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.

2. 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:

1234567891011 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.

3.final and Static

Many times it is easy to confuse the static with the final keyword, where static acts on the member variable to indicate that only one copy is saved, and final is used to ensure that the variable is immutable. Look at the following example:

12345678910111213141516 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();}

Running this code will reveal that the two J values are the same for each print, while the value of I is different. From here you can see the difference between final and static variables.

4. Why is an external local variable used in an anonymous inner class only a final variable?

This question is explained in the previous Article blog post, "Inside the Java class," which is not described here.

5. Questions about the final parameter

On the Internet "when you do not need to change an object variable as a parameter in a method, it is not appropriate to explicitly use Final declaration, which will prevent you from inadvertently modifying a variable outside of the calling method".

Because either the argument is a variable of the base data type or a variable of a reference type, using the final declaration does not achieve the effect described above.

See this example to make it clear:

The above code seems to make it possible to change the value of the variable I in the method after the final modification. As everyone knows, the method ChangeValue and the main method of the variable i is not a variable, because the Java parameter is passed by the value of the pass, for the basic type of variable, the equivalent of a direct copy of the variable. 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:

123456789101112131415 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");    }}

Running this code will reveal that the output is HelloWorld. Obviously, finishing with final does not prevent changing the contents of the object that the buffer points to in ChangeValue. Some say that if the final is removed, what if buffer is pointed to other objects in the ChangeValue. Friends with this idea can write their own code to try what the result is, if the final is removed, and then in the ChangeValue to point buffer to other objects, and does not affect the buffer in the main method, because Java is based on value passing, For reference variables, the reference value is passed, which means that the argument and the parameter point to the same object simultaneously, so that having the parameter point back to the other object has no effect on the argument.

Therefore, I personally do not agree with the statement on the final parameters circulated on the Internet.

Resources:

The idea of Java programming

A brief analysis of final keywords 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.