Reputation: 289
Hi I am playing around with creating java packages.
I created a package in a folder called admin with a file called Employee - this compiles correctly. Outside this package I have another java file that is importing this. Here is the source code.
import java.util.*;
// this works --> import admin.Employee;
import admin.*; // this doesn't
public class Hello {
public static void main(String[] args) {
Employee h = new Employee("James", 20000);
System.out.println(h.getName());
}
}
The weird thing is that the second import statement works fine but with the third one I get
Employee
./Employee.class
I am just using javac Hello.java to compile
the employee class is in package admin. The structure is
folder "admin" -> containing "Employee.class" and "Employee.java" outside this folder is the hello.java file.
package admin;
import java.util.*;
public class Employee
{
private static int nextId;
private int id;
private String name = "";
private double salary;
// static initialization block
static
{
Random generator = new Random();
// set nextId to a random number between 0 and 9999
nextId = generator.nextInt(10000);
}
// object initialization block
{
id = nextId;
nextId++;
}
// three overloaded constructors
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee(double s)
{
// calls the Employee(String, double) constructor
this("Employee #" + nextId, s);
}
// Default constructor
public Employee()
{
// name initialized to ""--see below
// salary not explicityl set--initialized to 0
// id initialized in initialization block
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
}
Upvotes: 1
Views: 22828
Reputation: 3086
Without changing the code (without adding package declarations, which is what I think the question was really asking), the basic fix would be to either:
When you tell it import admin.Employee, and it's in the same source folder, the compiler can infer you want that implicitly compiled. When you import admin.*, you need to include the .java file on the command-line, or include classpath to the .class file, for it to compile.
Upvotes: 0
Reputation: 29663
package admin;
import java.util.*;
public class Employee
{
also Employee.java
should be in directory admin
. e.g
./Hello.java
./admin/Employee.java
Upvotes: 1