说明:下面有三段代码,实际上后两段代码是将第一段代码拆分成两个java文件保存了,实现功能完全一样
问题:就我的理解,import java.util.*的作用是引入util下所有的类库,但是在第一段代码中,我还必须专门引入Date,否则编译就会报错,但如果像后两段代码一样,拆分开的,不用再单独的引入Date,一样可以编译成功,这是为什么?谢谢!代码1:import java.util.Date;
import java.util.*;public class EmployeeTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];

staff[0] = new Employee("Simon Lo",2450,2006,8,25);
staff[1] = new Employee("Seven Huang",3500,2006,06,01);
staff[2] = new Employee("Eric Yap",5000,2000,01,15);
for (Employee e : staff)
e.raiseSalary(5);

for (Employee e : staff)
System.out.printf("\nName=" + e.getName() + "\nSalary=" + e.getSalary() + "\nHireDay=" + e.getHireDay());
}
}class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month -1, day);
hireDay = calendar.getTime();
}

public String getName()
{
return name;
}

public double getSalary()
{
return salary;
}

public Date getHireDay()
{
return hireDay;
}

public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

private String name;
private double salary;
private Date hireDay;
}代码2:import java.util.*;
class Employee
{
private String name;
private double salary;
private Date hireDay;

public Employee(String n, double s, int year, int month, int day)
{
name  = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year,month - 1,day);
hireDay = calendar.getTime();
}

public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}

public void raiseSalary(double byPercent)
{
double raise = salary * byPercent /100;
salary = salary + raise;
}


//下面的main方法是用来测试Employee类的,并不会在整个程序中执行
public static void main(String args[])
{
Employee test = new Employee("Simon Lo",3000,2006,8,1);
test.raiseSalary(10);
System.out.println("There is some Unit Test blow this line:");
System.out.printf(test.getName() + "\t" + test.getSalary());
}}代码3:import java.util.*;public class EmployeeTest
{
public static void main(String args[])
{
Employee[] staff = new Employee[3];

staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

for (Employee e : staff)
e.raiseSalary(5);

for (Employee e : staff)
System.out.printf("Name=" + e.getName() + "\tsalary=" + e.getSalary() + "\thireDay=" + e.getHireDay() + "\n");
}
}

解决方案 »

  1.   

    我的机器上第一个去掉import java.util.Date才编译通过。
    我估计是在classpath中还有其他的Date类而且排名在jdk前面
    如:classpath = .;**\JDK1.6\lib\dt.jar;....
    如果在当前路径中存在自己定义的Date类文件,那么会报错
    EmployeeTest.java:29: 不兼容的类型
    找到: java.util.Date
    需要: Date
            hireDay = calendar.getTime();
      

  2.   

    哈哈哈……楼上的哥们儿!太感谢了!正如你所说的,同目录下存在一个Date.class文件!
    非常感谢!