GoodCoder666的个人博客

java final关键字语法

2020-04-01 · 3 min read
Java 语法

一、final类和方法

英文文档

原文:Java官方文档 -> Writing Final Classes and Methods
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.

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. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:

class ChessAlgorithm {
    enum ChessPlayer { WHITE, BLACK }
    ...
    final ChessPlayer getFirstPlayer() {
        return ChessPlayer.WHITE;
    }
    ...
}

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.

Note that 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.

总结

一个finalJava类或方法不能被继承。

例子

类(Integer源代码):

package java.lang;

import java.lang.annotation.Native;
// import ...
import static java.lang.String.UTF16;

public final class Integer extends Number // Final类不能被继承,但是可以extend或implement别的非final类
        implements Comparable<Integer>, Constable, ConstantDesc {
    @Native public static final int   MIN_VALUE = 0x80000000;
    @Native public static final int   MAX_VALUE = 0x7fffffff;
    @SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
	// 此处省略n行
    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    @Native private static final long serialVersionUID = 1360826667806852920L;
}

方法:

class ChessAlgorithm {
    enum ChessPlayer { WHITE, BLACK }
    // ...
    final ChessPlayer getFirstPlayer() { // 不能被继承,但是可以被调用
        return ChessPlayer.WHITE;
    }
    // ...
}

二、final属性/变量

Java中的final属性或变量类似于C/C++中的const变量,不能改变。
例子:

public class Information {
	private static final int WIDTH = 170, HEIGHT = 135; // final属性,可以为private
	public static final int SIZE = WIDTH * HEIGHT; // 也可以为public

	public int getDifference() {
		final int difference = WIDTH - HEIGHT; // 函数中的final变量
		return difference;
	}
}