The final keyword is an access modifier in Java, used to mark an element as unmodifiable, ensuring that it maintains its initial value or behavior during program execution. It applies to variables (cannot be reassigned), methods (cannot be overridden by subclasses), and classes (cannot be inherited). Benefits include immutability, security, performance optimization, and use in design patterns.
final keyword in Java
What is the final keyword?
The final keyword is an access modifier in Java, used to mark variables, methods or classes as unmodifiable. It guarantees that the marked element always maintains its initial value or behavior during program execution.
final variable
Declaring a variable as final means that the value of the variable cannot be changed once initialized. This means that the variable cannot be reassigned. This helps prevent accidental modification of data that could lead to errors. For example:
<code class="java">final int AGE = 25;</code>
final method
Declaring a method as final means that the method cannot be overridden by subclasses. This means that subclasses cannot modify the behavior of parent class methods. This is useful for ensuring consistent behavior of key methods. For example:
<code class="java">public final void printName() { System.out.println("John Doe"); }</code>
final class
Declaring a class as final means that the class cannot be inherited. This means that no other class can derive from this class. This is typically used to create utility classes or immutable objects. For example:
<code class="java">public final class MathUtils { public static int add(int a, int b) { return a + b; } }</code>
When to use the final keyword?
Using the final keyword has the following benefits:
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!