views:

323

answers:

8

Can an abstract class have a final method in Java?

+1  A: 

Yes, those methods cannot be overriden in subclasses. An example of that is the template method pattern...

pgras
You should give more explanation. Template method does not imply final, although it certainly makes life simpler.
kdgregory
Ok let say final is strongly recommended :) I consider it as an error not to use final for the template method...
pgras
+1  A: 

Yes it can ... need more characters

Adamski
+1  A: 

Of course, it means you can subclass it, but you cannot override that particular method.

omerkudat
A: 

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.

jjujuma
+4  A: 

Yes.

Hint: just fire up your favorite IDE (eclipse, netbeans, etc) and try it out. It will complain if it does not work.

Andreas_D
-1. The point of SO is not to tell people "try it yourself". It is a waste of effort and time if everyone who does an Internet search for this question has to launch an IDE and try it for themselves when someone can provide a complete and comprehensive answer to the question: http://stackoverflow.com/questions/1299398/1299434#1299434
Grant Wagner
Yes, your right and I accept the downvote, but this is keyur's third trivial question about abstract classes in row so I made an exemption.
Andreas_D
@Andreas_D: I missed that keyur had asked numerous questions on the same subject, and I had seen enough "why don't you try it for yourself" answers and comments this morning that I reacted a little too quickly with the downvote. I've removed it (does that mean you get your rep back?) since your answer isn't actually incorrect.
Grant Wagner
+8  A: 

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.

Bill the Lizard
excellent! Upvote for bringing up the template method pattern
ChrisAD
+2  A: 

Yes, it can. But the final method cannot be abstract itself (other non-final methods in the same class can be).

Mnementh
A: 

Yes.

Bombe