当前位置: 当前位置:首页 > 娱乐 > 27、详解 Java 中的 final 关键字 正文

27、详解 Java 中的 final 关键字

2024-04-28 17:46:39 来源:口口声声网 作者:休闲 点击:127次

27、详解 Java 中的 final 关键字

文章目录

  • 一、详解final 关键字(官方教程)
    • (1) final 方法
    • (2) final 类
    • (3) 常量(final 属性)
    • (4) 编译时常量(☆)
  • 二、键字final 可被使用在...
  • 三、详解细节
    • (1) 定义之后必须有值
    • (2) static final 赋值
    • (3) final 方法不能被重写,键字但可被继承使用
    • (4) 无需在 final 类中定义 final 方法
  • 四、详解Exercise

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

(1) final 方法

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


✏️ You might wish to make a methodfinal 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 constructorsshould 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 finalcannot be subclassed. This is particularly useful, for example, when creating an immutableclass like the String class.
在这里插入图片描述
📜 你同样可以把一整个类声明为final,被声明为final的类不能被继承(绝育了😊)
📜 Java 中的 String 类就是一个被final修饰的类,被final修饰的类是不可变的(immutable)
在这里插入图片描述

(3) 常量(final 属性)

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

static final double PI = 3.141592653589793;

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


✏️ Constants definedin 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 typeor a string(字符串) is defined as a constant and the value is known at compile time, the compiler replaces the constant nameeverywhere 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;    }}

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

作者:知识
------分隔线----------------------------
头条新闻
图片新闻
新闻排行榜