抽象类可以有最终方法吗?
问题描述:
抽象类可以用Java编写最终方法吗?
Can an abstract class have a final method in Java?
答
当然。有关示例,请查看模板方法模式。
Sure. Take a look at the Template method pattern for an example.
abstract class Game
{
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
扩展的类游戏
仍然需要实现所有抽象方法,但是它们无法扩展 playOneGame
因为它被宣布为final。
Classes that extend Game
would still need to implement all abstract methods, but they'd be unable to extend playOneGame
because it is declared final.
抽象类也可以包含既不是抽象也不是最终的方法,只是常规方法。这些方法必须在抽象类中实现,但是由实现者来决定扩展类是否需要覆盖它们。
An abstract class can also have methods that are neither abstract nor final, just regular methods. These methods must be implemented in the abstract class, but it's up to the implementer to decide whether extending classes need to override them or not.