Java 在Eclipse中运行一个子类,其父类具有主方法,但子类本身只是一个没有主方法的类
当我尝试运行没有main方法但与父类在同一个包中的子类,以便访问父类的main方法时,在Eclipse中没有运行子类a java应用程序的选项。Java 在Eclipse中运行一个子类,其父类具有主方法,但子类本身只是一个没有主方法的类,java,eclipse,inheritance,main-method,Java,Eclipse,Inheritance,Main Method,当我尝试运行没有main方法但与父类在同一个包中的子类,以便访问父类的main方法时,在Eclipse中没有运行子类a java应用程序的选项。 我看不出您为什么要这样做,但是,如果目的是学习如何从一个类运行另一个类的方法,您可以为MainMethodDemoParent创建构造函数,在其中打印消息,然后在MainMethodDemoChild中构建该类的实例。大概是这样的: //Package in which I have both the Parent and the Child clas
我看不出您为什么要这样做,但是,如果目的是学习如何从一个类运行另一个类的方法,您可以为
MainMethodDemoParent
创建构造函数,在其中打印消息,然后在MainMethodDemoChild
中构建该类的实例。大概是这样的:
//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
{
}
注意:如果这样做,则不需要在MainMethodDemoChild中扩展MainMethodDemoParent。如果出于某种原因您仍然希望扩展,那么如果方法名是公共的,您可以直接调用它们,或者使用super关键字
super.methodName()代码>我通过在eclipse中执行此操作来解决:
步骤1右键单击-->运行配置
步骤2:选中复选框-搜索主类时包含继承的主类
第三步-现在再次点击搜索。你应该能够找到你正在寻找的子类
我不想成为那个评论者,但没有理由这么做。运行parent方法,或者在child中创建另一个main
来执行其他操作。如果我是你,我不会恨我,谢谢你的评论,但是在Eclipse中有什么方法可以克服这个问题吗?通过CMD,您可以编译父类,该父类在同一.java文件中也包含子类。因此,创建了两个.class文件,一个用于父级,另一个用于子级。在执行子类时,您将获得输出。但是如何在Eclipse中实现这一点呢?
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();
}
}