从SuperClass强制SubClasses到@Override方法。 SuperClass中的方法必须有body

时间:2015-06-24 07:12:58

标签: java inheritance methods abstract method-overriding

我想从SubClasses强制@OverrideSuperClass方法。

SuperClass中的方法不能是abstract,因为我想提供一些基本的实现。

以下是我的代码示例:

public abstract class GenericModel<T extends GenericModel> {
    long id, counter;

    public String methodToBeOverridenInSubClass(String name) {
        // some basic implementation
        // rest details will be provided by subclass
        return name;
    }

}
public class SubClass extends GenericModel<SubClass> {
    @Override
    public String methodToBeOverridenInSubClass(String name) {
        switch (name) {
            case "name": return "Real name";
            default: super.methodToBeOverridenInSubClass(name);
        }
    }
}

这篇文章很有意思: MustOverrideException and MethodNotOverridenException

请给我一些帮助

2 个答案:

答案 0 :(得分:2)

您可以使用两种方法:

public abstract String methodToBeOverridenInSubClass(String name);


protected String commonMethodToUseInSubClasses(String name) {
    // some basic implementation
    return name;
}

这样子类必须覆盖methodToBeOverridenInSubClass,但你仍然可以使用commonMethodToUseInSubClasses中所有子类的公共代码。

答案 1 :(得分:2)

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. */

// ...
}