27、详解 Java 中的 final 关键字

简介: 27、详解 Java 中的 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;
    }
}

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

相关文章
|
21天前
|
设计模式 安全 Java
Java并发编程实战:使用synchronized关键字实现线程安全
【4月更文挑战第6天】Java中的`synchronized`关键字用于处理多线程并发,确保共享资源的线程安全。它可以修饰方法或代码块,实现互斥访问。当用于方法时,锁定对象实例或类对象;用于代码块时,锁定指定对象。过度使用可能导致性能问题,应注意避免锁持有时间过长、死锁,并考虑使用`java.util.concurrent`包中的高级工具。正确理解和使用`synchronized`是编写线程安全程序的关键。
|
1天前
|
存储 安全 Java
聊聊Java关键字synchronized(下)
聊聊Java关键字synchronized(下)
5 0
|
1天前
|
监控 安全 Java
聊聊Java关键字synchronized(上)
聊聊Java关键字synchronized
5 0
|
3天前
|
安全 Java 编译器
是时候来唠一唠synchronized关键字了,Java多线程的必问考点!
本文简要介绍了Java中的`synchronized`关键字,它是用于保证多线程环境下的同步,解决原子性、可见性和顺序性问题。从JDK1.6开始,synchronized进行了优化,性能得到提升,现在仍可在项目中使用。synchronized有三种用法:修饰实例方法、静态方法和代码块。文章还讨论了synchronized修饰代码块的锁对象、静态与非静态方法调用的互斥性,以及构造方法不能被同步修饰。此外,通过反汇编展示了`synchronized`在方法和代码块上的底层实现,涉及ObjectMonitor和monitorenter/monitorexit指令。
17 0
|
3天前
|
Java
两千字讲明白java中instanceof关键字的使用!
两千字讲明白java中instanceof关键字的使用!
12 0
|
3天前
|
Java 开发者
Java基础知识整理,注释、关键字、运算符
在日常的工作中,总会遇到很多大段的代码,逻辑复杂,看得人云山雾绕,这时候若能言简意赅的加上注释,会让阅读者豁然开朗,这就是注释的魅力!
37 11
|
8天前
|
安全 Java 开发者
Java并发编程:深入理解Synchronized关键字
【4月更文挑战第19天】 在Java多线程编程中,为了确保数据的一致性和线程安全,我们经常需要使用到同步机制。其中,`synchronized`关键字是最为常见的一种方式,它能够保证在同一时刻只有一个线程可以访问某个对象的特定代码段。本文将深入探讨`synchronized`关键字的原理、用法以及性能影响,并通过具体示例来展示如何在Java程序中有效地应用这一技术。
|
12天前
|
Java
Java关键字(1)
Java关键字(1)
|
1月前
|
安全 Java 编译器
Java 中的关键字
Java 中的关键字
75 0