Home Java JavaBase What is the function of java final keyword

What is the function of java final keyword

Nov 25, 2022 pm 04:26 PM
java final

In java, final can be used to modify classes, methods and variables. The final modified class means that the class cannot be inherited by any other class, which means that this class is a leaf class in an inheritance tree, and the design of this class has been considered perfect and does not need to be modified or extended. The method in the final modified class means that the class cannot be inherited by any other class and cannot be overridden; that is, the method is locked to prevent the inherited class from changing it. final modifies a variable in a class, indicating that the variable cannot be changed once it is initialized.

What is the function of java final keyword

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

What is the final keyword?

1. Structures that final can be used to modify: classes, methods, variables

2. Final is used to modify a class: this class Cannot be inherited by other classes.

When we need to prevent a class from being inherited, we can use final modification, but please note: All member methods in the final class will be implicitly defined as final methods .

For example: String class, System class, StringBuffer class

3. Final is used to modify the method: indicating that this method cannot be overridden

  • Function

    (1) Lock the method to prevent the inherited class from changing it.

    (2) Efficiency, in early Java versions, final methods will be converted into inline calls. However, if the method is too large, there may not be much improvement in performance. Therefore, in recent versions, final methods are no longer needed for these optimizations.

    The final method means "final, final" meaning, that is, this method cannot be overridden.

  • For example: getClass( ) in the Object class

4. final is used to modify variables. At this time, the variable is equivalent to Constants

  • final is used to modify attributes: the locations that can be considered for assignment are: explicit initialization, initialization in code blocks, initialization in constructors

  • Final modified local variables: Especially when final is used to modify the formal parameter, it indicates that the formal parameter is a constant. When we call this method, we assign an actual parameter to the constant parameter. Once assigned, the value of this parameter can only be used in the method body and cannot be reassigned.

  • If final modifies a reference type, after initializing it, it can no longer point to other objects or its address cannot change (because the value of the reference is An address, final requires a value, that is, the value of the address does not change), but the content of the object pointed to by the reference can change. Essentially the same thing.

5. When using the final keyword to declare classes, variables and methods, you need to pay attention to the following points:

  • Use final In front of the variable, it means that the value of the variable cannot be changed. In this case, the variable can be called a constant.

  • final is used in front of a method to indicate that the method cannot be overridden (if a subclass creates a method with the same name, the same return value type, and the same parameter list as the parent class) , only the implementation in the method body is different to achieve functions different from those of the parent class. This method is called method rewriting, also known as method overwriting. Just understand it here, we will explain it in detail later in the tutorial).

  • final is used in front of a class to indicate that the class cannot have subclasses, that is, the class cannot be inherited.

final modified variable

The variable modified by final becomes a constant and can only be assigned a value once, but the variable modified by final There is a difference between local variables and member variables.

  • Final modified local variables must be assigned a value before they can be used.

  • Final modified member variables that are not assigned a value when declared are called "blank final variables". Empty final variables must be initialized in a constructor or static code block.

Note: It is wrong to say that a variable modified by final cannot be assigned a value. Strictly speaking, a variable modified by final cannot be changed. Once the initial value is obtained, the final variable The value cannot be reassigned.

public class FinalDemo {
    void doSomething() {
        // 没有在声明的同时赋值
        final int e;
        // 只能赋值一次
        e = 100;
        System.out.print(e);
        // 声明的同时赋值
        final int f = 200;
    }
    // 实例常量
    final int a = 5; // 直接赋值
    final int b; // 空白final变量
    // 静态常量
    final static int c = 12;// 直接赋值
    final static int d; // 空白final变量
    // 静态代码块
    static {
        // 初始化静态变量
        d = 32;
    }
    // 构造方法
    FinalDemo() {
        // 初始化实例变量
        b = 3;
        // 第二次赋值,会发生编译错误
        // b = 4;
    }
}

Lines 4 and 6 of the above code declare local constants. Line 4 just declares that there is no assignment, but it must be assigned before use (see line 6 of the code). In fact, it is best for local constants to be in Initialized at the same time as declaration. Lines 13, 14, 16, and 17 of the code all declare member constants. Lines 13 and 14 of the code are instance constants. If it is a blank final variable (see line 14 of the code), it needs to be initialized in the constructor (see line 27 of the code). Lines 16 and 17 of the code are static constants. If it is a blank final variable (see line 17 of the code), it needs to be initialized in a static code block (see line 21 of the code).

In addition, no matter what kind of constant, it can only be assigned once. See line 29 of the code for b constant assignment. Because b has been assigned once before, a compilation error will occur here.

The difference between final modified basic type variables and reference type variables

当使用 final 修饰基本类型变量时,不能对基本类型变量重新赋值,因此基本类型变量不能被改变。 但对于引用类型变量而言,它保存的仅仅是一个引用,final 只保证这个引用类型变量所引用的地址不会改变,即一直引用同一个对象,但这个对象完全可以发生改变。

下面程序示范了 final 修饰数组和 Person 对象的情形。

import java.util.Arrays;
class Person {
    private int age;
    public Person() {
    }
    // 有参数的构造器
    public Person(int age) {
        this.age = age;
    }
    // 省略age的setter和getter方法
    // age 的 setter 和 getter 方法
}
public class FinalReferenceTest {
    public static void main(String[] args) {
        // final修饰数组变量,iArr是一个引用变量
        final int[] iArr = { 5, 6, 12, 9 };
        System.out.println(Arrays.toString(iArr));
        // 对数组元素进行排序,合法
        Arrays.sort(iArr);
        System.out.println(Arrays.toString(iArr));
        // 对数组元素赋值,合法
        iArr[2] = -8;
        System.out.println(Arrays.toString(iArr));
        // 下面语句对iArr重新赋值,非法
        // iArr = null;
        // final修饰Person变量,p是一个引用变量
        final Person p = new Person(45);
        // 改变Person对象的age实例变量,合法
        p.setAge(23);
        System.out.println(p.getAge());
        // 下面语句对P重新赋值,非法
        // p = null;
    }
}

从上面程序中可以看出,使用 final 修饰的引用类型变量不能被重新赋值,但可以改变引用类型变量所引用对象的内容。例如上面 iArr 变量所引用的数组对象,final 修饰后的 iArr 变量不能被重新赋值,但 iArr 所引用数组的数组元素可以被改变。与此类似的是,p 变量也使用了 final 修饰,表明 p 变量不能被重新赋值,但 p 变量所引用 Person 对象的成员变量的值可以被改变。

注意:在使用 final 声明变量时,要求全部的字母大写,如 SEX,这点在开发中是非常重要的。

如果一个程序中的变量使用 public static final 声明,则此变量将称为全局变量,如下面的代码:

public static final String SEX= "女";

final修饰方法

final 修饰的方法不可被重写,如果出于某些原因,不希望子类重写父类的某个方法,则可以使用 final 修饰该方法。

Java 提供的 Object 类里就有一个 final 方法 getClass(),因为 Java 不希望任何类重写这个方法,所以使用 final 把这个方法密封起来。但对于该类提供的 toString() 和 equals() 方法,都允许子类重写,因此没有使用 final 修饰它们。

下面程序试图重写 final 方法,将会引发编译错误。

public class FinalMethodTest {
    public final void test() {
    }
}
class Sub extends FinalMethodTest {
    // 下面方法定义将出现编译错误,不能重写final方法
    public void test() {
    }
}

上面程序中父类是 FinalMethodTest,该类里定义的 test() 方法是一个 final 方法,如果其子类试图重写该方法,将会引发编译错误。

对于一个 private 方法,因为它仅在当前类中可见,其子类无法访问该方法,所以子类无法重写该方法——如果子类中定义一个与父类 private 方法有相同方法名、相同形参列表、相同返回值类型的方法,也不是方法重写,只是重新定义了一个新方法。因此,即使使用 final 修饰一个 private 访问权限的方法,依然可以在其子类中定义与该方法具有相同方法名、相同形参列表、相同返回值类型的方法。

下面程序示范了如何在子类中“重写”父类的 private final 方法。

public class PrivateFinalMethodTest {
    private final void test() {
    }
}
class Sub extends PrivateFinalMethodTest {
    // 下面的方法定义不会出现问题
    public void test() {
    }
}

上面程序没有任何问题,虽然子类和父类同样包含了同名的 void test() 方法,但子类并不是重写父类的方法,因此即使父类的 void test() 方法使用了 final 修饰,子类中依然可以定义 void test() 方法。

final 修饰的方法仅仅是不能被重写,并不是不能被重载,因此下面程序完全没有问题。

public class FinalOverload {
    // final 修饰的方法只是不能被重写,完全可以被重载
    public final void test(){}
    public final void test(String arg){}
}

final修饰类

final 修饰的类不能被继承。当子类继承父类时,将可以访问到父类内部数据,并可通过重写父类方法来改变父类方法的实现细节,这可能导致一些不安全的因素。为了保证某个类不可被继承,则可以使用 final 修饰这个类。

下面代码示范了 final 修饰的类不可被继承。

final class SuperClass {
}
class SubClass extends SuperClass {    //编译错误
}

因为 SuperClass 类是一个 final 类,而 SubClass 试图继承 SuperClass 类,这将会引起编译错误。

final 修饰符使用总结

1. final 修饰类中的变量

表示该变量一旦被初始化便不可改变,这里不可改变的意思对基本类型变量来说是其值不可变,而对对象引用类型变量来说其引用不可再变。其初始化可以在两个地方:一是其定义处,也就是说在 final 变量定义时直接给其赋值;二是在构造方法中。这两个地方只能选其一,要么在定义时给值,要么在构造方法中给值,不能同时既在定义时赋值,又在构造方法中赋予另外的值。

2. final 修饰类中的方法

说明这种方法提供的功能已经满足当前要求,不需要进行扩展,并且也不允许任何从此类继承的类来重写这种方法,但是继承仍然可以继承这个方法,也就是说可以直接使用。在声明类中,一个 final 方法只被实现一次。

3. final 修饰类

表示该类是无法被任何其他类继承的,意味着此类在一个继承树中是一个叶子类,并且此类的设计已被认为很完美而不需要进行修改或扩展。

For members in final classes, you can define them as final or not. As for methods, since the class they belong to is final, they naturally become final. You can also explicitly add a final method to the final class, which is obviously meaningless.

Recommended tutorial: "java tutorial"

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

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Java Performance Optimization and Profiling Techniques Java Performance Optimization and Profiling Techniques Jul 31, 2025 am 03:58 AM

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

A Guide to Java Flight Recorder (JFR) and Mission Control A Guide to Java Flight Recorder (JFR) and Mission Control Jul 31, 2025 am 04:42 AM

JavaFlightRecorder(JFR)andJavaMissionControl(JMC)providedeep,low-overheadinsightsintoJavaapplicationperformance.1.JFRcollectsruntimedatalikeGCbehavior,threadactivity,CPUusage,andcustomeventswithlessthan2%overhead,writingittoa.jfrfile.2.EnableJFRatsta

Best Practices for Writing Maintainable Java Code Best Practices for Writing Maintainable Java Code Jul 31, 2025 am 06:21 AM

Follow naming specifications to make the code as easy to read as prose; 2. The method should be small and focused, and a single responsibility is easy to test and reuse; 3. Write meaningful comments to explain "why", rather than obvious operations; 4. Prioritize immutability and packaging to prevent external accidental modifications; 5. Exceptions should be properly handled without ignoring and providing clear information; 6. Unit tests should be clearly named and cover key paths; 7. Reasonable use of modern Java features such as var and Stream to improve readability; 8. Organization of package structures layered by functions to improve project navigation efficiency - these practices jointly ensure that Java code is maintained for a long time.

See all articles