1. 阅读ManagerTest代码
(1)代码
import java.util.*
package test;
/**
* This program demonstrates inheritance.
* @version 1.21 2004-02-21
* @author Cay Horstmann
*/
public class ManagerTest
{
public static void main(String[] args)
{
// construct a Manager object
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
// fill the staff array with Manager and Employee objects
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}
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;
}
class Manager extends Employee
{
/**
* @param n the employee's name
* @param s the salary
* @param year the hire year
* @param month the hire month
* @param day the hire day
*/
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
private double bonus;
}
(2)UML类图
(3)文件第26行e.getSalary(),到底是调用Manager类的还是Employee类的getSalary方法?
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
e.getSalary()会根据具体的类执行对应的代码,子类的同名方法会覆盖父类的方法
staff[0]执行的是Manager类的getSalary方法,staff[1]和staff[2]执行的是Employee类的getSalary方法
(4) Manager类的构造函数使用super调用父类的构造函数实现了代码复用,这样有什么好处?为什么不把父类构造函数中的相关代码复制粘贴到Manager的构造函数中,这样看起来不是更直观吗?
使用super调用父类的构造函数减少代码重复现象,代码更加简洁,也减少了打代码的时间。
调用子类的构造方法时会先调用父类的无参构造函数,若父类无无参构造函数,那么在子类的构造方法中必须显式地调用父类的构造方法。因为子类继承了父类,那么就默认的含有父类的公共成员方法和公共成员变量,这些方法和变量在子类里不再重复声明。如果初始化子类的时候,不初始化父类,那么你通过子类调用父类方法或变量的时候会抛出异常。
(5)该代码中哪里体现了多态的好处?请说明。
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
在调用对象的e.getName()和getSalary()方法时,根据对象实例调用相应方法,无需用if语句判断实例对象类型,代码简洁,方便阅读