Home > Java > javaTutorial > body text

What is the use of final in java

下次还敢
Release: 2024-04-25 23:27:14
Original
833 people have browsed it

The final keyword in Java makes variables, methods and classes unchangeable. Variables cannot be reassigned, methods cannot be overridden, and classes cannot be inherited.

What is the use of final in java

The role of final in Java

In Java, the final keyword is an access modifier, used Used to mark variables, methods, and classes to make them immutable.

Variables

When declaring a final variable, it must be initialized at the time of declaration, and the variable cannot be reassigned later. This ensures that the value of the variable remains unchanged throughout the execution of the program.

For example:

<code class="java">final int MY_CONSTANT = 10;
MY_CONSTANT++; // 编译错误:不能重新赋值 final 变量</code>
Copy after login

Method

When final is applied to a method, it means that the method cannot be overridden by subclasses. This is useful to prevent subclasses from modifying key methods in the parent class.

For example:

<code class="java">class Parent {
    final void printMessage() {
        System.out.println("Parent message");
    }
}

class Child extends Parent {
    // 编译错误:无法覆盖 final 方法
    void printMessage() {
        System.out.println("Child message");
    }
}</code>
Copy after login

Class

If final is applied to a class, it means that the class cannot be inherited. This prevents other classes from subclassing this class.

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

// 编译错误:无法继承 final 类
class Child extends FinalClass {
    // ...
}</code>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!