从超类静态主创建子类 [英] Create subclass from superclass static main

查看:87
本文介绍了从超类静态主创建子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的抽象类(SuperClass).我想有一个main方法,该方法将是每个子类的默认主体,并且将执行相同的操作,但要使用派生并调用它的适当子类对象.

I have a generic, abstract class (SuperClass). I want to have there a main method, that would be a default main for each subclass and would do the same, but with proper subclass object that derived and called it.

赞:

 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对象?

And now I would like to be able to run the SubClass as standalone program, that executes the default main derived from the SuperClass. How to instantiate the proper SubClass object in the main method?

  • 我不能做新手,因为在SuperClass中我不知道SubClass
  • 的实际名称
  • 我无法使用反射来完成此操作,因为我无法从SuperClass(
  • I cannot do just new because in SuperClass I don't know the actual name of a SubClass
  • I cannot do it using reflection, because I cannot get the name of the SubClass from a static method implemented in the SuperClass (Getting the name of a sub-class from within a super-class)

在C ++中,AFAIR中有一个类似virtual的方法修饰符,我想这在这里很有用.用Java怎么做?

In C++, AFAIR, there is something like virtual modifier for a method, that I guess would be useful here. How to do in in Java?

推荐答案

静态方法不会被继承,如果您希望子类成为应用程序的入口点,请在子类中编写main方法.

Static methods are not inherited, if you want your subclass to be your application entry point, program the main method in the subclass.

这篇关于从超类静态主创建子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆