How to use the final keyword in Java

Source: Internet
Author: User
Tags abstract anonymous constant constructor inheritance modifier object model stringbuffer

Final has the meaning of "unchangeable" and can modify non-abstract classes, non-abstract member methods, and variables.

Classes modified with final cannot be inherited, and no subclass exists.
The methods modified with final cannot be overwritten by the quilt class ).
A variable modified with final indicates a constant and can only be assigned once (when a variable is declared ).

Note:

Final cannot be used to modify constructor methods, because the concept of "method override" applies only to member methods of classes, rather than constructor methods of classes, there is no overwrite relationship between the constructor of the parent class and the constructor of the child class. Therefore, using final to modify the constructor is meaningless.

The methods modified by private in the parent class cannot be overwritten by the methods of the quilt class. Therefore, it can be understood that the methods of the private type are of the final type by default.

Final class

Define the class as final so that the class cannot be inherited. The specific application scenarios are as follows:

Instead of a class designed specifically for inheritance, there is a complex call relationship between methods of the class itself. If you create any subclass of these classes, the subclass may incorrectly modify the implementation details of the parent class.
For security reasons, the implementation details of the class cannot be extended.
When creating an object model, make sure that this class will not be extended.

For example, the java. lang. String class in JDK is defined as the final type.

Public final class String {...}

Final method

In some cases, for security reasons, the parent class does not allow subclass to overwrite a method. In this case, you can declare this method as the final type.

For example, in the java. lang. Object class of JDK, the getClass () method is of the final type, while the equals () method is not of the final type.

All Object subclasses can override the equals () method, but cannot override the getClass () method.

Final variable

Variables modified with final indicate constants whose values do not change.

For example, two constants are defined in the java. lang. Integer class in JDK.

Public static final int MIN_VALUE = 0x80000000;

Public static final int MAX_VALUE = 0x7fffffff;

Final variables have the following features:

The final modifier can modify static variables, member variables, and local variables to represent static constants, instance constants, and local constants respectively.

Public class Demo {public static final int MAX_VALUE = 23; // static constant public static final int MIN_VALUE = 10; // static constant private final Date birthday = new Date (); // member constant}


Static constants are generally named after uppercase letters, separated.

The final modified member variables must be initialized.

Public class FinalTest {final int a = 1; // The Default initialization of a member constant is static final int B = 2; // The Default initialization of a static constant is final int c; // member constant static final int d; // static constant public FinalTest () {c = 3; // The member constant is not initialized by default, can be initialized in the constructor} static {d = 4; // static constants are not initialized by default, can be initialized in the static code block }}


The final variable can only be assigned a value once. If a variable of the reference type is modified with final, the variable can only always reference one object, but can change the content of the object.

Public class FinalTest {String str = ""; public void print () {System. out. println (str);} public static void main (String [] args) {final FinalTest finalTest = new FinalTest (); finalTest. str = "xixihaha"; finalTest. print ();}}

 

Summary:

In actual programs, constants are defined using final modifiers to improve program Security, code maintainability, and code readability;




Analysis of final keywords in Java

When talking about final keywords, many people may be familiar with them, and they may often use final keywords when using anonymous internal classes. 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

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

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

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.