java 包含主要方法的Java扩展类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16949484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:28:53  来源:igfitidea点击:

Java Extending class containing main method

java

提问by user1107888

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. The code runs without problem and Hello World is printed which to me is surprising. 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.

我的任务是运行代码,然后解释输出。文件的名称是Factorial.java。代码运行没有问题,并且打印了 Hello World,这让我感到惊讶。在输入代码之前,我认为它不会编译,因为正在扩展的父类应该在另一个文件中,但现在我不太确定。希望得到一些澄清。

回答by Ravi Thapliyal

Java allows you to define multiple classes within a single .javafile with the condition that you can have at mostone publicclass and ifyou do then the name of that public class must match the name of the .javafile. In your case, the class declared publicis Factorialand hence your file name has to be Factorial.java.

Java允许您在单个中定义多个类.java文件,就可以具备的条件至多一个public,如果你这样做,然后是公共类的名称必须与的名称相匹配.java的文件。在您的情况下,声明的类publicFactorial,因此您的文件名必须是Factorial.java.

The inheritanceis working as usual here and the public static void main()is inherited by Factorialwhich is why you see your output on executing java Factorial.

继承在这里工作像往常一样与public static void main()被继承了Factorial这就是为什么你看到在执行你的输出java Factorial

回答by Philipi Willemann

You can have more than one class in the same file, but only one public , as Baseisn't a public class, but it's not a recommended practice.

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