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:
final String NAME = "John Doe"; NAME = "Jane Doe"; // 编译错误
Method
final method cannot be overridden by subclasses. This helps prevent unexpected behavior by overriding critical methods. For example:
final void printName() { System.out.println("John Doe"); }
Class
final class cannot be inherited. This helps ensure that the class is unmodifiable and prevents the creation of its subclasses. For example:
final class Person { // ... }
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:
public static final int MAX_AGE = 100;
Anonymous inner class
Using final in an anonymous inner class can capture external variables. For example:
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); } });
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!