第27篇:详解 Java 中的 final 关键字

简介: 📋 final 类只是不能被继承,是可以实例化的📋 ① 不是 final 类;② 有一个 final 的方法;③ 该 final 方法不能被重写(但是可以被继承)【final 方法不能被子类重写,但可以被子类使用】 能用不可改

一、final 关键字(官方教程)

(1) final 方法

✏️ You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden(重写) by subclasses. The Object class does this—a number of its methods are final.
📜 你可以把一个类的部分或全部方法声明为是final方法。使用final关键字声明一个方法表示这个方法不能够被子类重写。Object 基类就是这样做的,Object 类的某些方法就是final方法


✏️ You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object.
📜 你可能想要把某个方法声明为final方法,因为该方法的实现是不应该被修改的。你可能想要把某个方法声明为final方法,因为该方法所在的类的对象的一致状态至关重要。


✏️ Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.
📜 需要在构造方法中调用的方法通常应该被声明为final,若构造方法调用了非 final 的方法,哪子类就有可能会重写该非 final 方法(此操作导致的后果是令人惊讶和不希望的)


(2) final 类

✏️ You can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
在这里插入图片描述
📜 你同样可以把一整个类声明为final,被声明为final的类不能被继承(绝育了😊)
📜 Java 中的 String 类就是一个被final修饰的类,被final修饰的类是不可变的(immutable)
在这里插入图片描述

(3) 常量(final 属性)

✏️ The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
📜 static 关键字和 final 关键字共同使用可以用来声明常量(被 staticfinal 共同修饰的成员变量是常量)
📜 final修饰符表示:属性的值不能被改变

static final double PI = 3.141592653589793;
✒️ 上面代码中的 PI 就是一个常量
✒️被 static修饰表示它在 JVM 中只有一份内存【 类变量在程序运行过程中只占用一份固定的内存(存储在方法区)】
✒️ 被 final修饰表示它的值是不能被修改的

✏️ Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore_
📜 被final关键字修饰的常量不能被重新赋值,如果你偏要这样干的话,编译器会给你一个编译时错误。
📜 按照惯例,常量名通常是大写字母,若常量名由多个单词组成:多个单词之间用【下划线分隔】

public static final String BASE_URL = "https://iloveyou.com";

(4) 编译时常量(☆)

✏️ If a primitive type or a string(字符串) is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant.
📜 如果一个基本数据类型或字符串被声明为常量,并且该常量的值在编译的时候就知道值的话:编译器会用该常量的值替换代码中各个地方的该常量名【类似 C 语言中的宏替换】

✏️ If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
📜 如果外界的常量的值发生变化(例如:如果立法规定 π 实际上应该是 3.975),您将需要重新编译任何使用该常量的类来获取当前值。

二、final 可被使用在...

📗 若不希望类被继承,可用 final 修改该类
📗 若不希望父类的某个方法被子类重写,可用 final 修饰该方法
📗 若不希望属性的值被修改,可用 final 修饰该属性
📗 若不希望局部变量的值被修改,可用 final 修饰该局部变量
在这里插入图片描述
在这里插入图片描述

三、细节

(1) 定义之后必须有值

📋 被final修饰的属性定义之后就必须确定(没有默认值)
📋 可以定义候给予初始值
📋 可以在初始化块中给予初始值
📋 可以在构造器中给予初始值

public class FinalKeyword {
    // 没有被 final 修饰的属性定义之后不必须给值(有默认值)
    public String baseURL;
    // 定义时赋值
    // public final String BASE_NETWORK_URL = "";

    public final String BASE_NETWORK_URL; /* ERROR */

    public FinalKeyword() { // 构造器中赋值
        // BASE_NETWORK_URL = "";
    }

    { // 初始化块中赋值
        // BASE_NETWORK_URL = "";
    }
}

(2) static final 赋值

📋 如果被final修饰的属性是静态的,则初始化的位置只能是:① 定义的时候;② 在静态初始化块中

✒️ 不能在 构造器中给 常量static final)赋值
✒️ 常量必有 static
✒️ 构造器与对象实例挂钩
✒️ static 与对象实例毫无关系
public class FinalKeyword {
    // public static final String BASE_URL = ""; // Right
    public static final String BASE_URL;

    static {
        BASE_URL = ""; // Right
    }
}

(3) final 方法不能被重写,但可被继承使用

📋 final 类只是不能被继承,是可以实例化的

📋 ① 不是 final 类;② 有一个 final 的方法;③ 该 final 方法不能被重写(但是可以被继承)【final 方法不能被子类重写,但可以被子类使用能用不可改

public class Whatever {
    public final void test() {
        System.out.println("Whatever: final void test()");
    }

    public static void main(String[] args) {
        // Whatever: final void test()
        new Son().sonTest();
    }
}

class Son extends Whatever {
    public void sonTest() {
        // 使用父类的 final 方法
        super.test();
    }
}

(4) 无需在 final 类中定义 final 方法

📖 若一个类已经是 final 了,则该类中的方法无需定义为 final 方法

public final class Whatever {
    public void test() {
        System.out.println("final 类中定义的方法无需手动加上 final 关键字");
        System.out.println("final 类都不能被继承, 咋可能重写里面的方法嘛!");
    }
}

📖 final 不能修饰构造方法

📖 static final 搭配使用,效果更佳

📖 包装类(Integer、Double、Float、Boolean)都是 final

📖 String 也是 final

在这里插入图片描述

四、Exercise

public final class Whatever {
    public int test(final int x) {
        // 被 final 修饰的局部变量 x 不能被第二次赋值赋值
        // ++x; // ERROR
        return x + 1;
    }
}

结束!如有错误,请不吝赐教

相关文章
|
14天前
|
Java API
【JAVA】final、finally、finalize 有什么区别?
【JAVA】final、finally、finalize 有什么区别?
|
21小时前
|
小程序 Java 容器
03|Java基础语法:讲解标识符、关键字、变量、数据类型、运算符、控制语句(条件分支、循环)
03|Java基础语法:讲解标识符、关键字、变量、数据类型、运算符、控制语句(条件分支、循环)
7 0
|
21小时前
|
Java
深入浅出Java基础语法:标识符、关键字、变量、数据类型、运算符与控制语句
深入浅出Java基础语法:标识符、关键字、变量、数据类型、运算符与控制语句
5 0
|
11天前
|
Java
final 在 java 中有什么作用?
final 在 java 中有什么作用?
|
11天前
|
存储 安全 Java
【亮剑】Java并发编程涉及`ThreadLocal`、`Volatile`、`Synchronized`和`Atomic`四个关键机制
【4月更文挑战第30天】Java并发编程涉及`ThreadLocal`、`Volatile`、`Synchronized`和`Atomic`四个关键机制。`ThreadLocal`为每个线程提供独立变量副本;`Volatile`确保变量可见性,但不保证原子性;`Synchronized`实现同步锁,保证单线程执行;`Atomic`类利用CAS实现无锁并发控制。理解其原理有助于编写高效线程安全代码。根据业务场景选择合适机制至关重要。
|
11天前
|
Java 编译器
【Java探索之旅】this 关键字 解决你的成员变量困惑
【Java探索之旅】this 关键字 解决你的成员变量困惑
17 0
|
11天前
|
Java
【Java探索之旅】我与Java的初相识(完):注释,标识符,关键字
【Java探索之旅】我与Java的初相识(完):注释,标识符,关键字
5 0
|
12天前
|
Java
Java里的关键字 __final
Java里的关键字 __final
|
14天前
|
Java 编译器
【JAVA】volatile 关键字的作用
【JAVA】volatile 关键字的作用
|
14天前
|
Java
【JAVA面试题】final关键字的作用有哪些
【JAVA面试题】final关键字的作用有哪些