Home  >  Article  >  Java  >  How to use final in java

How to use final in java

下次还敢
下次还敢Original
2024-04-26 20:54:16988browse

Final is used in Java to declare immutable variables, non-overridable methods, and non-inheritable classes. It also helps in declaring constants and capturing external variables. The main usage is summarized as follows: final variable: unchangeable, read-only. final method: cannot be overridden, but can be implemented. Final class: cannot be inherited, but its methods can be called. final constant: cannot be changed, usually represented by uppercase letters. final anonymous inner class: can capture external variables.

How to use final in java

Usage of final in Java

final is a keyword in Java, used to declare variables and methods and classes.

Variables

final variables are read-only and cannot be changed once assigned. This helps prevent accidental changes to sensitive data. For example:

<code class="java">final String NAME = "John Doe";
NAME = "Jane Doe"; // 编译错误</code>

Method

final method cannot be overridden by subclasses. This helps prevent unexpected behavior by overriding critical methods. For example:

<code class="java">final void printName() {
    System.out.println("John Doe");
}</code>

Class

final class cannot be inherited. This helps ensure that the class is unmodifiable and prevents the creation of its subclasses. For example:

<code class="java">final class Person {
    // ...
}</code>

Other uses

final can also be used to declare constants and anonymous inner classes.

Constant

final constant is unchangeable and can be declared in classes, methods and interfaces. For example:

<code class="java">public static final int MAX_AGE = 100;</code>

Anonymous inner class

Using final in an anonymous inner class can capture external variables. For example:

<code class="java">JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
    final String name = "John";
    
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Hello, " + name);
    }
});</code>

Points to note

  • Once a final variable is declared, its value cannot be changed.
  • Final methods cannot be overridden, but can be implemented.
  • The final class cannot be inherited, but its methods can be called in subclasses.
  • Final constants are usually represented by uppercase letters.

The above is the detailed content of How to use final in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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