Knowledge of the final keyword that you may not know about Java basics

Usage of final modifier:

  1. final can modify variables Modified variables cannot be reassigned after being assigned an initial value
  2. final can be modified methods Modified methods cannot be overridden
  3. final can modify a class Modified class cannot derive subclasses

assignment of final variables

  1. When defining a final variable, assign it an initial value
  2. Assign final value in non-static initial block
  3. Assigning final value in the constructor
    We can find through the javap tool that these three methods are essentially assigning an initial value to final in the constructor.
    From the following figure, we can know that final needs to be assigned an initial value.
    insert image description here

final is a macro constant

For a final variable, no matter it is a class variable, instance variable, local variable, as long as it defines final and assigns an initial value to final, then the final variable is essentially no longer a variable,
it becomes a direct variable

Let's take an example

String st=new String("Helloworld");

Here is a very simple code
and its loading order is

  1. Create a space in the heap to store Helloworld
  2. Create a String type st in the stack and assign it to null
  3. Referring to st the space where Hellowrld is stored,
    what is the final loading order?
final String st="Helloworld";

The answer is to directly determine that "hellowrld" is in st when compiling,
so is this "Helloworld" in the stack? The
answer is of course not .
insert image description here

final methods cannot be overridden

According to the parent delegation mechanism, we can know that a class will load its parent class first when it is loaded,
but if the method of the parent class is modified by final, then the child class will not have permission to access the method of the parent class.
For the child class, this method does not exist so cannot be overridden

local variables in inner classes

Regardless of whether it is an anonymous inner class or a normal inner class, the local variables accessed by any inner class have final modification by default, which
means that inner classes cannot modify local variables.

Why is this so?

We all know the life cycle of local variables.
When the method ends, the local variable disappears with it,
but the
inner class may generate an implicit closure, and the closure will make the local variable continue to exist away from the method it is in.

Simply put, the local variable is sent to your inner class and it has not been sent to you. If you want to fix a variable that has been modified, there will definitely be a problem.

Guess you like

Origin blog.csdn.net/qq_47431361/article/details/123258339