抽象类里面的动态抽象类

时间:2015-12-07 14:11:54

标签: java class generics inheritance abstract

我的这个类构造有问题。我想以某种方式将Superclass Super2的Extended类类型作为Super1构造函数中的参数,但我不知道如何。

我想满足这些要求:

  • 在doStuffWithDoStuff()
  • 中初始化Super2扩展类的实例
  • 不要将带有Super2实例的参数添加到doStuffWithDoStuff()
abstract class Super2 {
    Super2(String test) {
    }
    public void exit() {
    }
}
abstract class Super1 {
    abstract doStuff(Class<? extends Super2> super);
    protected doStuffWithDoStuff() {
         Super2 super2 = new Super2("test");
         doStuff(super2);
         super2.exit();
    }
}

用法:

class Test1 extends Super2 {
    Test1() {
        super();
    }
    public void doStuff() {
    }
}
class Test2 extends Super1 {
    doStuff(Test1 test) {
        test.doStuff();
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你的问题有点过于深奥,无法理解你想要达到的目标。以下工作是否符合您所描述的要求?

abstract class Super1 {

    private Class<? extends Super2> super2Type;

    protected Super1(Class<? extends Super2> super2Type) {
        this.super2Type = super2Type;
    }

    abstract doStuff(Class<? extends Super2> super);

    protected doStuffWithDoStuff() {
         Super2 super2 = super2Type.newInstance(); //Error handling omitted for brevity
         doStuff(super2);
         super2.exit();
    }
}