Final keyword action case of Java Foundation

Time:2021-10-24

Function of final keyword

The final keyword can be used to modify references, methods, and classes.

1. Final keyword modification class

When a class is decorated with the final keyword, the class cannot be inherited. Code examples are as follows:

Therefore, when defining a class, you need to think about whether the class will be inherited in the future.

2. Final keyword modification method

When a method is modified with the final keyword, the method cannot be overridden. Code examples are as follows:

 Note: the private method of a class will be implicitly specified as the final method.

3. Final keyword modifies variables

The variable modified by the final keyword cannot be modified after initialization. Code examples are as follows:

If it is a variable of reference type, it cannot point to another object after its initialization. Code examples are as follows:

  • Modify member variables and local variables

Member variables and local variables modified by final need to be assigned before use.

be careful:

  1. The member variables and local variables modified by the final keyword must be initialized, or compilation errors will occur.
  2. There are two ways to assign values to the member variables modified by the final keyword: 1. Direct assignment. 2. Assign an initial value in the construction method.
  3. If the modified member variable is a basic type, the value of the variable previously indicated will not change.
  • Modifier reference variable

The reference variable value modified by the final keyword cannot change the reference point, that is, it can only point to the same address, but can modify the content pointing to the object.

This is the end of this article on the role of the final keyword of Java foundation. For more final content of Java foundation, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!