Home > Java > JavaBase > What is the function of java final keyword

What is the function of java final keyword

青灯夜游
Release: 2022-11-25 16:26:26
Original
24601 people have browsed it

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;
    }
}
Copy after login

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;
    }
}
Copy after login

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

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

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

public static final String SEX= "女";
Copy after login

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() {
    }
}
Copy after login

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

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

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

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

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

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

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

final修饰类

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

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

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

因为 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!

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