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.
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
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!