【问题标题】:Run a CHILD in Eclipse of which the PARENT class has the main method but the CHILD class itself is just a class without the main method在 Eclipse 中运行一个 CHILD,其 PARENT 类具有 main 方法,但 CHILD 类本身只是一个没有 main 方法的类
【发布时间】:2020-08-02 06:01:27
【问题描述】:
//Package in which I have both the Parent and the Child class
package learningJava;
public class MainMethodDemoParent 
{
  //Main method of the parent class
    public static void main(String... args)
    {
        System.out.print("This is the Parent class");
    }
}

//Child class which extends the Parent class
package learningJava;
public class MainMethodDemoChild extends MainMethodDemoParent

{

}

当我尝试运行没有main方法但与父类在同一个包中的子类以便我可以访问父类的main方法时,在Eclipse中没有RUN选项Child 类是一个 java 应用程序。

【问题讨论】:

  • 我讨厌成为那个评论者,但有没有理由这样做。要么运行父方法,要么在子进程中创建另一个 main 来执行其他操作。
  • 如果我是你,我不会恨我,感谢你的评论,但有什么方法可以在 Eclipse 中克服这个问题?通过 CMD,您可以在同一个 .java 文件中编译具有子类的父类。因此,创建了两个 .class 文件,一个为父级,另一个为子级。在执行 Child 类时,您将获得输出。但是如何在 Eclipse 中实现呢?

标签: java eclipse inheritance main-method


【解决方案1】:

我通过在 eclipse 中这样做解决了: Step-1 右键-->运行配置

Step-2 勾选-Inclue继承的mains when search main class。

第 3 步 - 现在再次点击搜索。您应该能够找到您要查找的子类。

【讨论】:

    【解决方案2】:

    我看不出您为什么要这样做,但是,如果目的是学习如何从另一个类运行方法,您可以为MainMethodDemoParent 创建一个构造函数,打印您的消息在那里,然后在MainMethodDemoChild 中构建该类的一个实例。像这样的:

    class MainMethodDemoParent 
    {
        public MainMethodDemoParent()
        {      
            System.out.print("This is the Parent class");
        }
    }
    
    //Child class which extends the Parent class MainMethodDemoChild
    class MainMethodDemoChild
    {
      public static void main(String[] args)
      {
        new MainMethodDemoParent();
      }
    }
    

    注意:如果这样做,您不需要在 MainMethodDemoChild 中扩展 MainMethodDemoParent。如果由于某种原因还想扩展,可以直接调用公开的方法名,或者使用 super 关键字super.methodName();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-29
      • 2014-04-21
      • 1970-01-01
      • 2016-03-18
      • 2013-01-19
      • 2014-10-30
      • 1970-01-01
      • 2015-08-08
      相关资源
      最近更新 更多