Packages for Beginners
When a classfile that belongs to a package, then
package PackageName;
is included in the source code of that file. So when jvm is invoked by writing
java PackageName.classfilename
it gets executed.
Is it that "package PackageName" guarantees 开发者_开发技巧the jvm that this classfile belongs to this very package? Because if we omit the "package PackageName" statement, then jvm still finds out the class file but gives
Exception in thread "main" java.lang.NoClassDefFoundError: Classfilename
wrongname PackageName/ClassfileName
It means jvm finds out the file but there is some reason for which it considers that this classfile has a wrong name.
The package declarations on your classes must match the folder structure that you have for your code. Packages are used by the JVM for several "tasks", from the visibility of methods, to the resolution of situations where two classes could have the same name. A NoClassDefFoundError actually means the JVM cannot find the class with the package you gave it. If you ommit the package definition on the class, and run the program like: java ClassFileName The JVM will find the class, as long as you're running the java command from the folder where your class is.
Also... package names should be all lowercase and Class names should start with an Uppercase. :) Conventions are really helpful when someone else is reading your code!
Hope the comment helped.
The class file needs to exist on the file system in the same hierarchy as is defined in the package name. If you remove the package name, I believe you must have the file in the root folder of your jar to work in the "unnamed" package. Likely you removed the package line from the source file but still left the class definition inside of the PackageName
folder.
精彩评论