为什么编译器需要.java后缀,但解释器不需要.class后缀? [英] Why compiler needs .java suffix but interpreter doesn't need .class suffix?

查看:78
本文介绍了为什么编译器需要.java后缀,但解释器不需要.class后缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要编译Foo.java: javac Foo.java

To compile Foo.java: javac Foo.java

运行程序: java Foo

To run the program : java Foo

为什么编译器需要 .java 后缀,但解释器不需要 .class 后缀?

Why compiler needs .java suffix but interpreter doesn't need .class suffix?

推荐答案

正如其他几个答案所述,Java编译器将文件名作为参数,而解释器将类名.因此,您将 .java 扩展名提供给编译器,因为它是文件名的一部分,但您不将其提供给解释器,因为它不是类名的一部分.

As a couple of other answers have explained, the Java compiler takes a file name as an argument, whereas the interpreter takes a class name. So you give the .java extension to the compiler because it's part of the file name, but you don't give it to the interpreter because it's not part of the class name.

但是,您可能想知道,为什么他们不只是以不同的方式设计Java解释器,以便采用文件名?答案是,并非总是从 .class 文件加载类.有时它们来自JAR存档,有时它们来自互联网,有时它们是由程序动态构建的,依此类推.一个类可以来自任何可以提供所需二进制数据的来源

But then, you might wonder, why didn't they just design the Java interpreter differently so that it would take a file name? The answer to that is that classes are not always loaded from .class files. Sometimes they come from JAR archives, sometimes they come from the internet, sometimes they are constructed on the fly by a program, and so on. A class could come from any source that can provide the binary data needed to define it. Perhaps the same class could have different implementations from different sources, for example a program might try to load the most up-to-date version of some class from a URL, but would fall back to a local file if that failed. The designers of Java thought it best that when you're trying to run a program, you don't have to worry about having to track down the source that defines the class you're running. You just give the fully qualified class name and let Java (or rather, its ClassLoaders) do the hard work of finding it.

这篇关于为什么编译器需要.java后缀,但解释器不需要.class后缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆