Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use final in Java

Shulou Source: shulou.com Published: 2022-06-02 09:36:23 10月02日 Update

This article mainly introduces "how to use final in Java". In daily operation, I believe many people have doubts about how to use final in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use final in Java". Next, please follow the editor to study!

1. Final definition

Final translated into Chinese means "final". It is a common keyword in Java. Objects modified with final are not allowed to modify or replace their original values or definitions.

For example, after a class is modified by final, it cannot be inherited by other classes.

As shown in the following figure:

2. Four uses of final

There are four uses of final:

Modifier class

Modification method

Modified variable

Modification parameter

2.1. Modifier class final class Animal {}

Description: classes modified by final are not allowed to be inherited, indicating that such a design is perfect and does not need to be modified and extended.

2.2. Modification method public class FinalExample {public final void sayHi () {System.out.println ("Hi~");}}

Description: the method modified by final means that the function provided by this method has met the current requirements, does not need to be extended, and does not allow any classes inherited from this class to override this method.

2.3. Modifier variable public class FinalExample {private static final String MSG = "hello"; / /.}

Description: when final modifies a variable, it means that the attribute cannot be modified once it is initialized.

2.4. Modifier parameter public class FinalExample {public void sayHi (final String name) {System.out.println ("Hi," + name);}}

Note: when final modifies a parameter, it means that this parameter is not allowed to be modified within the whole method.

3. Final action.

Using final to modify a class can prevent it from being inherited by other classes, such as the String class in JDK code is modified by final, thus preventing it from being inherited by other classes, resulting in internal logic being broken.

Some of the source codes of String class are as follows:

At this point, the study on "how to use final in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Methods parameters learning variables more this method help primitive practical next code function keyword function object that is properties common meaning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Huawei Microsoft NVidia macOS