抽象类可以有最终方法吗? [英] Can an abstract class have a final method?

查看:230
本文介绍了抽象类可以有最终方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象类可以用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.

这篇关于抽象类可以有最终方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆