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

后端 未结 5 1692
青春惊慌失措
青春惊慌失措 2020-12-21 03:40

To compile Foo.java: javac Foo.java

To run the program : java Foo

Why compiler needs .java suffix but interpre

相关标签:
5条回答
  • 2020-12-21 04:16

    Adding to David Zaslavsky's explanation:

    The java source code are not necessarily from .java files either. We can have a compiler that takes source code from difference character streams, as in the API javax.tools.JavaCompiler.

    The cmd line util javac happens to be working with file sources only, so it desires file paths.

    0 讨论(0)
  • Every language will have syntax and semantics which will establish rules and understanding between similar parties. Like how english has words, tenses, verbs etc., to simplfy communication between two english speaking parties. Java specification established syntax and semantics that compiler can understand only java files and interpreter can understand only .class files.

    0 讨论(0)
  • 2020-12-21 04:29

    The Java compiler takes a filename as input, hence Foo.java.

    the Java interpreter takes the fully qualified class name and searches the classpath and current directory for the class. If you use java Foo.class it would search for the class named "class" in the package "Foo", and return NoClassDefFoundError if the class is in the default package, as I understand from your example

    0 讨论(0)
  • 2020-12-21 04:36

    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.

    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.

    0 讨论(0)
  • 2020-12-21 04:36

    Foo.java is the file name while simply "Foo" is the class name (not a file name). The default ClassLoader will search your current working directory for the file Foo.class and load it.

    0 讨论(0)
提交回复
热议问题