【问题标题】:Dynamic abstract class inside abstract class抽象类中的动态抽象类
【发布时间】:2016-03-12 04:13:34
【问题描述】:

我对这个类结构有疑问。我想以某种方式将超类 Super2 的扩展类类型作为参数提供给 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();
    }
}

【问题讨论】:

  • Super3 的定义在哪里?是不是笔误?
  • 不能直接实例化抽象类,必须通过实例化子类来实例化。 Super2 super = new Super2("test");不起作用,您可能会使用匿名内部类。另外:Super1 扩展了 Super3,而您没有 Super3 类..
  • super是java中的关键字
  • @Stultuske 是的,我知道,这就是为什么我写了“我必须以某种方式在 Super1 的构造函数中提供扩展类”,以便我可以实例化子类而不是超类。
  • @Jens 是的,这只是一个错误使用的示例名称

标签: java class generics inheritance abstract


【解决方案1】:

我认为你的问题有点太深奥了,无法理解你到底想要达到什么目的。以下工作(我相信它符合您描述的要求)吗?

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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2017-01-30
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多