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.
'Java 배우기' 카테고리의 다른 글
Summary of Inheritance 상속 요약 (0) | 2016.01.05 |
---|---|
Abstract Methods and Classes 추상적 메소드와 클래스 (0) | 2016.01.05 |
Object as a Superclass 수퍼클래스로서의 객체 (0) | 2016.01.05 |
Using the Keyword super 키워드 super 사용하기 (0) | 2016.01.05 |
Hiding Fields (0) | 2016.01.05 |
댓글