Reputation: 173
I am studying java packages. I successfully created a package pack that contained single .class file Hello.class. Now I want to add another class file into the same package. I named the new java class as Goodbye.java and compiled it into the same directory "pack" via
javac -d ./bin Goodbye.java
command. bin directory contains pack directory. The I compile test.java file containing main function via
javac -cp ./bin test.java
command. Compilation works fine. But when I enter
java test
command. I get
Hello, world
Exception in thread "main" java.lang.NoClassDefFoundError: pack/Goodbye
at test.main(test.java:9)
Caused by: java.lang.ClassNotFoundException: pack.Goodbye
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 1 more
Can anybody explain what I did wrong in this case? I am working on ubuntu 14.04 and doing everything in the terminal.
Both Hello.java and Goodbye.java files are located in
/home/username/apps/src
directory. Corresponding class files are inside
/home/username/apps/bin/pack
directory. pack directory was created by
javac -d ./bin
command. Contents of the Hello.java file
package pack;
public class Hello
{
public static void HelloMessage()
{
System.out.println("hello, world");
}
}
It works ok. For its corresponding class file gets loaded Contents of Goodbye.java file is
package pack;
public class Goodbye
{
public static void message()
{
System.out.println("bye");
}
}
test.java file which imports the package is located at /home/username/apps directory. It has the following lines of code
import pack.*;
public class test
{
public static void main(String args[])
{
Hello.HelloMessage();
Goodbye.message();
}
}
Any help is highly appreciated.
Upvotes: 2
Views: 8781
Reputation: 10373
My understanding of your class files is like the following tree:
/home/username/apps/bin
|
+-- pack
| |
| +--- Hello.class
| |
| +--- Goodbye.class
|
+-- test.class
Then go to /home/username/apps/bin
and call
java -cp . test
With -cp
you add the current directory to search for classes. This should always be the root of your packages. Then refer to your main class.
BTW: According to the Java naming conventions, class names should start with a capital letter, like Test
.
Update: Updated the class file location.
Upvotes: 1
Reputation: 84
You need to set classpath of two locations because you have class files in two different locations:
You can do it by using -cp option of javac command. You need to put semicolon between more than one classpaths like below:
java -cp .;./bin test
Upvotes: 0