Why if I try to execute a class containing the main() method from within its package I obtain an error message?

时间秒杀一切 提交于 2019-12-02 12:33:41

If you notice in your source file, there's a package statement for Main.java like this

package mainPkg;
public class Main{

}

When you're compiling, you're saying that my Main class has a namespace called mainPkg. Now that you defined a namespace for your class any attempt to access Main should have the namespace prefix like mainPkg.Main which we usually refer to as Fully Qualified Class Name.

When you're in build/classes and invoking java mainPkg.Main, JVM will first check if there's a mainPkg sub-folder in the current directory. As it's there already it goes inside and finds the Main, verifies if the fully qualified class name matches with what we gave in java command, if it's same it'll load your class and execute your main().

When you're running the same java mainPkg.Main from build/classes/mainPkg, this time there's no sub-folder called mainPkg within mainPkg, so it will throw the error that you're seeing.

Hope this makes sense :)

it works, infact I obtain this output (at certain times there is an exception but this is another problem not related at what I am asking at this time):

While that is not the objective of your question, the exception occurs because the oracle driver jar file is not in the classpath. To fix the error add the jar file ojdbc6.jar to the classpath using the -cp option.

But if I enter into the build/classes/mainPkg/ directory (the package) it don't works and I obtain an "impossible to find or load main class" error message?

mainPkg.Main is the fully qualified name of your java class. You need to provide that to the java runtime environment so it can find and run that class. Main alone is not enough since there could be many java files in the classpath with the class name Main.

More information is available in the documentation

By default, the first argument without an option is the name of the class to be called. A fully qualified class name should be used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!