import的疑问

cashlu cashlu 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
说明:下面有三段代码,实际上后两段代码是将第一段代码拆分成两个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");
}
}
...全文
评论 2
收藏 已收藏
分享
返回顶部
cashlu
Java SE 62,620 成员 307,251 内容