Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an abstract class have a final method?

Can an abstract class have a final method in Java?

like image 326
keyur Avatar asked Aug 19 '09 11:08

keyur


People also ask

How do you call a final method of an abstract class?

The same is true for abstract methods, you cannot make the final in Java. An abstract method must be overridden to be useful and called but when you make the abstract method final it cannot be overridden in Java, hence there would be no way to use that method.

Why can't an abstract method be declared final?

If you declare a class abstract, to use it, you must extend it and if you declare a class final you cannot extend it, since both contradict with each other you cannot declare a class both abstract and final if you do so a compile time error will be generated.

Can we have final abstract method in Java?

The answer is simple, No, it's not possible to have an abstract method in a final class in Java.

Can abstract class have final variable?

An abstract class may contain non-final variables. Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables.


2 Answers

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.

like image 65
Bill the Lizard Avatar answered Nov 08 '22 07:11

Bill the Lizard


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

like image 22
Mnementh Avatar answered Nov 08 '22 08:11

Mnementh