Can an abstract class have a final method in Java?
Yes, those methods cannot be overriden in subclasses. An example of that is the template method pattern...
Of course, it means you can subclass it, but you cannot override that particular method.
Yes. The abstract
modifier makes it possible to omit some of the implementation of a class (i.e. have some abstract
methods) but does not impose any restrictions on you.
Yes.
Hint: just fire up your favorite IDE (eclipse, netbeans, etc) and try it out. It will complain if it does not work.
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();
}
}
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.
Yes, it can. But the final method cannot be abstract itself (other non-final methods in the same class can be).