Frage

Maybe this question may be splitting hairs, but when I compile a file from command line like :

javac MyClass.java

then afterward I cannot run it by saying

java MyClass.class

I have to call:

java MyClass

What is the motivation for this notation?

War es hilfreich?

Lösung

Because you run a class on the classpath, which may be contained inside a jar for example. You couldn't use your syntax in that case.

Andere Tipps

Java compiler needs a compilation unit; this is by default (at least) a java source file, with the whole of classes defined in it and its dependencies.

Java interpreter (the jvm) needs a single class with a main method as entry point of the execution - it must start somewhere.

You'd have to ask Sun (now Oracle) for the development history, but I do want to point out that for folks who are just using Java rather than developing Java, "java DoSomething" is easier to remember, and to type, than "java DoSomething.class"

There is no way to run a Java program that is not a class. For that reason, there is no reason to mandate typing the ".class". You might also invoke a class from within a JAR on your path, or directly, but it's still instantiating a class (possibly a "default" class from the Manifest).

Because the name of the class is MyClass and not MyClass.class. And when running java you specify the CLASS NAME and not the PATH to the actual compiled file. For more in depth knowledge I guess Sun & Oracle will have to answer :)

Imagine that you have a class named package and you have a class named Class, in a package named package,

--CurrentFolder
    --package
         Class.class
      package.class

so executing java package.class may lead to an undecidability to the compiler!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top