Home > Java > javaTutorial > body text

Final all-round in-depth analysis

巴扎黑
Release: 2017-07-19 13:14:13
Original
1134 people have browsed it


Java has a keyword final. A variable can be declared as a final type. A final type variable can only be assigned once. If a final variable is assigned a value repeatedly, a compilation error will occur.


What is the meaning of the final keyword?

final is a reserved keyword in Java that can declare member variables, methods, classes and local variables. Once you make the reference declaration final, you will not be able to change the reference. The compiler will check the code and if you try to initialize the variable again, the compiler will report a compilation error.

What is a final variable?

Any member variables or local variables (variables in methods or code blocks are called local variables) that are declared final are called final variables. Final variables are often used with the static keyword as constants. The following is an example of a final variable:

public static final String LOAN = "loan";

LOAN = new String("loan") //invalid compilation error

final variable is read-only.

What is a final method?

Final can also declare methods. Adding the final keyword in front of a method means that this method cannot be overridden by methods of subclasses. If you think the function of a method is complete enough and does not need to be changed in subclasses, you can declare the method as final. Final methods are faster than non-final methods because they are statically bound at compile time and do not need to be dynamically bound at runtime. The following is an example of a final method:

class PersonalLoan{
    public final String getName(){
        return "personal loan";
    }
}
 
class CheapPersonalLoan extends PersonalLoan{
    @Override
    public final String getName(){
        return "cheap personal loan"; //compilation error: overridden method is final
    }
}
Copy after login

What is a final class?

A class modified with final is called a final class. Final classes are usually functionally complete and they cannot be inherited. There are many classes in Java that are final, such as String, Interger and other wrapper classes. The following is an example of the final class:

final class PersonalLoan{
 
    }
 
    class CheapPersonalLoan extends PersonalLoan{  //compilation error: cannot inherit from final class
 
}
Copy after login

Benefits of the final keyword

The following summarizes some of the key words to use final Benefits of words

The final keyword improves performance. Both JVM and Java applications cache final variables.

Final variables can be safely shared in a multi-threaded environment without additional synchronization overhead.

Using the final keyword, the JVM will optimize methods, variables and classes.

Effectively Final

A variable will be considered effectively if and only if it is in the following situations

1. Not declared as final

2 .The value is only assigned once

The simplest way to explaineffectively finalis to imagine that it has been modified with final. If modified in this way, the program will still run without error (when the compilation is passed) ^0^), and is consistent with the original running result, then this variable can be said to be effectively final.

Benefits of final

Restricting local variables to valid immutable variables is designed to allow developers to better handle concurrency and thread-safe development. Mutable fields are always a potential source of concurrency problems if not managed properly.

Use of final keyword

I think it is a good habit to declare variables, method parameters, etc. as final. It can be a good reminder to other people in the team not to modify it lightly. Put this aside, declare it as final, and the compiler will optimize it well when compiling it into a class file.

There are many arguments against "it is incorrect to use the final keyword in source files to achieve optimization of class files". It is strongly recommended to read Robert Simons Jr's "Hardcore Java 》Details on the use and optimization of final keywords.

In an application, the final keyword makes the intention of your code look obvious, and it will not be changed after the declaration, which is very safe.

public class FinalTest {

    public static final int N_ITERATIONS = 10_00_000;

    public static String testFinal() {
        final String a = "a";
        final String b = "b";
        return a + b;
    }

    public static String testNonFinal() {
        String a = "a";
        String b = "b";
        return a + b;
    }

    public static void main(String[] args) {
        long tStart, tElapsed;

        tStart = System.currentTimeMillis();
        for (int i = 0; i < N_ITERATIONS; i++)
            testFinal();
        tElapsed = System.currentTimeMillis() - tStart;
        System.out.println("Method with finals took " + tElapsed + " ms");

        tStart = System.currentTimeMillis();
        for (int i = 0; i < N_ITERATIONS; i++)
            testNonFinal();
        tElapsed = System.currentTimeMillis() - tStart;
        System.out.println("Method without finals took " + tElapsed + " ms");

    }

}
Copy after login

Running results:

Method with finals took 5 ms
Method without finals took 273 ms
Copy after login

Summary

Final can make the variables you declare safer and make your code safer It seems clearer, and Effective Java also advocates the use of immutable classes.


The above is the detailed content of Final all-round in-depth analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!