java final关键字语法

一、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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值