One, final
class and method
English document
原文: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.
to sum up
One final
of the Java
class or method can not be inherited.
example
Class ( Integer
source code):
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;
}
method:
class ChessAlgorithm {
enum ChessPlayer {
WHITE, BLACK }
// ...
final ChessPlayer getFirstPlayer() {
// 不能被继承,但是可以被调用
return ChessPlayer.WHITE;
}
// ...
}
Two, final
attributes/variables
Java
The final
attributes or variables in is similar C/C++
to the const
variables in and cannot be changed.
example:
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;
}
}