I write a source file and put that public class in a package :
package abc;
public class Employee
{
// Constructor
public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
// Methods
public String getName()
{
return this.name;
}
public double getSalary()
{
return this.salary;
}
// instance field
private String name;
private double salary;
}
Then I try to compile it using command: javac Employee.java , it generates a .class file in the same directory as the source file
Now I try to use this package, so I write a source file :
import abc.*;
public class HelloWorld
{
public static void main(String args[]){
//System.out.println("hello world");
Employee aEmployee = new Employee("David",1000);
System.out.println(aEmployee.getName() + aEmployee.getSalary());
}
}
I try to compile it using: javac HelloWorld.java , but it has a error says : package abc doesn’t exist
I have the following questions:
1) Why did this error happen ?
2) How to solve this problem ?
3) Each time when I package some classes, where can I find the package to use afterwards
I’ve read some docs about this, but that’s so complex, can somebody explain it simply ?
This is because the java compiler looks for a directory tree when it tries to load a package, either in the classpath or in a jar file. This means for a package called
abc.foo.bar, it will look for the directory tree:/abc/foo/barand expect classes that belong to that package to be there. You’ve compiled your Employee class but when you import it, the compiler looks for a directoryabcin your classpath, and it’s not there.You need to make sure when you compile the Employee class, its classfile is in a directory
abcwhich is somewhere in your classpath. The simplest thing may be to create a directory calledabc, then move the Employee.java file into theabcdirectory, then compile:This will create a Employee.class file in the
abcdirectory. Then you can compile your HelloWorld:In the directory tree that you’ve named your package. See the later part of the response to
1).