简体   繁体   English

包含main方法的Java Extending类

[英]Java Extending class containing main method

I have the following code as part of an assignment 我将以下代码作为作业的一部分

class Base {
  public static void main(String[] args){
    System.out.println("Hello World");
  }
}

public class Factorial extends Base{


}

My task is run the code and then explain the output.The name of the file is Factorial.java . 我的任务是运行代码,然后解释输出。文件的名称是Factorial.java The code runs without problem and Hello World is printed which to me is surprising. 代码运行没有问题,打印Hello World对我来说是令人惊讶的。 Before typing the code, I was thinking that it wont compile because the parent class, which is being extended should be in another file but now I am not so sure. 在输入代码之前,我认为它不会编译,因为正在扩展的父类应该在另一个文件中,但现在我不太确定。 Would appreciate soome clarification. 非常感谢soome澄清。

Java allows you to define multiple classes within a single .java file with the condition that you can have at most one public class and if you do then the name of that public class must match the name of the .java file. Java允许您在单个中定义多个类.java与您最多可以有一个条件文件public类, 如果你做那么公共类的名称必须与的名称相匹配.java文件。 In your case, the class declared public is Factorial and hence your file name has to be Factorial.java . 在您的情况下,声明为public的类是Factorial ,因此您的文件名必须是Factorial.java

The inheritance is working as usual here and the public static void main() is inherited by Factorial which is why you see your output on executing java Factorial . 继承在这里正常工作,并且Factorial继承了public static void main() ,这就是为什么你在执行java Factorial看到你的输出。

您可以在同一个文件中拥有多个类,但只有一个公共类,因为Base不是公共类,但不是推荐的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM