英文:
Java File runs with java FileName.java command but doesn't compile with javac Filename.java
问题
Java文件只能有一个公共类,但是使用java
命令运行时,它会执行指定的公共类,而忽略其他类的存在。这就是为什么使用java B.java
运行时没有错误,因为它执行的是B
类的main
方法。但是,使用javac
编译器进行编译时,它会检查并强制要求每个公共类都在其自己的文件中,这就是为什么在javac B.java
编译时会出现错误,因为class A
没有在A.java
文件中声明。
英文:
File name: B.java
public class B
{
public static void main(String[] args){}
}
public class A{}
java B.java
runs without errorjavac B.java
gives a compile error:class A needs to be declared in a file A.java
I understand that a java file can not have more than one public class, but why can a java file run without error using the java
command when you get compile errors for the code using javac
?
答案1
得分: 8
Java-11+ 允许启动单文件源代码程序 而无需编译。 您可以从这篇文章了解更多信息。 根据规范,如果文件中的第一个类具有 main
方法,它将执行,而不关心文件中的其他 public
类。 因此,如果您更改文件中类的顺序并尝试 java B.java
,它将失败。
英文:
Java-11+ allows launching Single-File Source-Code programs without compiling. You can learn more about it from this article. As per the specification, if the first class in the file has main
, it executes the same without caring for other public
classes in the file. Thus, if you change the order of classes in the file and try java B.java
, it will fail.
答案2
得分: 1
-
我的猜测,这只是一个猜测,因为我没有广泛使用Java 11,是这样的:
-
“javac”命令生成的类文件可以组合成一个大程序,因此在程序中可能会有多个对类A的引用“其他地方”。正是这种通用性导致了每个源文件只能有一个公共类的限制(尽管坦率地说,我不明白为什么编译B.java不能生成A.class和B.class)
-
“java”命令处理一个单一的源文件。从这个角度来看,A是否是public都是无关紧要的;A都可以在单个文件(同一包中!)中使用。
英文:
My guess, and it is only a guess since I haven't used Java 11 extensively, is that:
-
The "javac" command produces class files that can be combined into a large program, and thus there could be multiple references to class A "elsewhere" in the program. It is this generality that produces the restriction on one public class per source file (though frankly I don't see why compiling B.java cannot result in A.class and B.class)
-
The "java" command processes a single source file. From that point of view it is irrelevant whether A is public or not; A can be used from within the single file (same package!) in any case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论