我在面试中问过以下问题,我很想知道答案.
我有一个基类,'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 ...."部分