我的基类每次都在我的代码中更改.我怎么能克服这个?

Aak*_*eef -3 java inheritance extends

我在面试中问过以下问题,我很想知道答案.

我有一个基类,'GeneratorBaseClass',由Generator扩展.我被问到的问题是创建一个新的基类'GeneratorBaseClass2'并让Generator更改以在运行时扩展它(无需更改Generator).所以,作为代码的一个例子

public class GeneratorBase1 {
    public GeneratorBase1(){
        System.out.println("Generator Base 1 is used");
    }
}

public class Generator  extends  GeneratorBase1{

    public Generator() {
        //will call the appropriate super class
    }
    public static void main(String[] args){
        Generator test=new Generator();


    }


}
Run Code Online (Sandbox Code Playgroud)

我想让Generator在运行时选择一个新的GeneratorBase,所以改为

public class GeneratorBase2 {
    public GeneratorBase2(){
        System.out.println("Generator Base 2 is used");
    }
}
Run Code Online (Sandbox Code Playgroud)

可以更改Generator的形式,但每次基类更改时都不得更改.这是关于允许在运行时选择基类,我不想只改变"extends ...."部分

Gee*_*eek 5

我正在努力尝试这里.但问题是暧昧的.为什么有人想要一次又一次地更改基类?这可能是因为基类提供的功能在运行时发生了变化.如果是这种情况,则有两种可能的情况.

  1. 基类应该是一个接口,仅此而已.

  2. 您应该在基类中组合更改的功能,并让实现在运行时更改,就像策略设计模式的工作方式一样.