java override方法_java-从SuperClass强制子类使用@Override方法. Su...

也许您正在寻找的内容可以通过Template method pattern解决.

在其中创建一个实现了一个方法的父类,该方法描述了一个调用另一个方法(步骤)的过程.这些步骤是抽象的,因此它们由子类实现.

来自维基百科的示例:

/**

* An abstract class that is common to several games in

* which players play against the others, but only one is

* playing at a given time.

*/

abstract class Game {

protected int playersCount;

abstract void initializeGame();

abstract void makePlay(int player);

abstract boolean endOfGame();

abstract void printWinner();

/* A template method : */

public final void playOneGame(int playersCount) {

this.playersCount = playersCount;

initializeGame();

int j = 0;

while (!endOfGame()) {

makePlay(j);

j = (j + 1) % playersCount;

}

printWinner();

}

}

//Now we can extend this class in order

//to implement actual games:

class Monopoly extends Game {

/* Implementation of necessary concrete methods */

void initializeGame() {

// Initialize players

// Initialize money

}

void makePlay(int player) {

// Process one turn of player

}

boolean endOfGame() {

// Return true if game is over

// according to Monopoly rules

}

void printWinner() {

// Display who won

}

/* Specific declarations for the Monopoly game. */

// ...

}

class Chess extends Game {

/* Implementation of necessary concrete methods */

void initializeGame() {

// Initialize players

// Put the pieces on the board

}

void makePlay(int player) {

// Process a turn for the player

}

boolean endOfGame() {

// Return true if in Checkmate or

// Stalemate has been reached

}

void printWinner() {

// Display the winning player

}

/* Specific declarations for the chess game. */

// ...

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值