运行结果
name=Carl Cracker,salary=78750.0,hireDay=Tue Dec 15 00:00:00 CST 1987 name=Harry Hacker,salary=52500.0,hireDay=Sun Oct 01 00:00:00 CST 1989 name=Tony Tester,salary=42000.0,hireDay=Thu Mar 15 00:00:00 CST 1990
1. raiseSalary方法有什么用?
答:求出工资的涨幅,计算出5%涨的薪水的金额
2.1 代码中3个Employee对象调用raiseSalary方法所执行的代码一样吗?
答:执行的代码一样
2.2返回结果一样吗?为什么?
答:返回的结果不一样,因为根据
double raise = salary * byPercent / 100;
每一个Employee的初始salary是不一样的,因此得到的涨薪的金额是不同的。
3.1 能不能将raiseSalary定义为static?
不能。如果一个成员被声明为static,它就能够在它的类的任何对象创建之前被访问,而不必引用任何对象。显然,要调用raiseSalary方法,必须需要先创建对象,才可以调用raiseSalary方法,使得方法是有意义的。
3.2 结合该例子,你觉得一般来说什么样的方法应该声明为static?
直接通过类名调用,该方法通常声明为static。至于变量,如果声明为static,通常表示需要常驻内存的。定义类本身的变量,或者类方法,而不是实例变量或者实例方法的时候用static,例如调用Math类中的PI,其申明就为static。
public static final double PI = 3.14159265358979323846;
4. 进阶要求:使用Java8中的日期类,替换掉Employee类中的hireDay。
运行结果
name=Carl Cracker,salary=78750.0,hireDay=Tue Dec 15 00:00:00 CST 1987 name=Harry Hacker,salary=52500.0,hireDay=Sun Oct 01 00:00:00 CST 1989 name=Tony Tester,salary=42000.0,hireDay=Thu Mar 15 00:00:00 CST 1990
修改后的代码入下:
import java.util.*; import java.time.DayOfWeek; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; 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.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } } class Employee { public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; LocalDate date = LocalDate.of(year, month, day);// GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); hireDay = date;// hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public LocalDate getHireDay() // public Date getHireDay() { //{ return hireDay; //return hireDay; } //} public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } private String name; private double salary; private LocalDate hireDay;//private Date hireDay; }