【发布时间】:2012-07-04 00:34:50
【问题描述】:
我有一个通用的抽象类 (SuperClass)。我希望有一个main 方法,这将是每个子类的默认 main 方法,并且会做同样的事情,但使用正确的子类对象派生并调用它。
像这样:
public abstract class SuperClass {
// some code here...
public static void main(String args[]) {
// here instantiate the subclass
// extending this SuperClass, and call
// some methods
}
}
public SubClass extends SuperClass {
// here just implement some
// abstract methods from SupeClass
// and NOT implement main()
}
现在我希望能够将SubClass 作为独立程序运行,它执行从SuperClass 派生的默认main。如何在main方法中实例化正确的SubClass对象?
- 我不能只做新的,因为在
SuperClass我不知道SubClass的实际名称 - 我不能使用反射来做到这一点,因为我无法从
SuperClass(Getting the name of a sub-class from within a super-class) 中实现的静态方法中获取SubClass的名称
在 C++ 中,AFAIR 中有类似 virtual 修饰符的方法,我想这在这里很有用。用Java怎么做?
【问题讨论】:
标签: java methods static instantiation derived-class