public class ManagerTest {
public static void main(String[] args) {
//创建了一个Manager对象,并设置了一个奖金属性
Manager boss = new Manager("Car 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);
for(Employee e : staff){
//运行第一个e的getSalary()方法时,是调用Manager对象的方法,这里java虚拟机会自动判断,这也是java的特性 **多态** 的表现
System.out.println("name="+e.getName()+",salary="+e.getSalary());
}
}
}
import java.util.Date;
import java.util.GregorianCalendar;
public 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 += raise;
}
}
public class Manager extends Employee {
private double bonus;
//Manager(子类)继承Employee(父类,也叫超类)
public Manager(String n,double s,int year,int month,int day){
/*
这里的super(n,s,year,month,day);语句是调用父类Employee中含有n,s,year,month,day参数的构造器的简写。所以super语句必须是子类构造器的第一条语句.
就是说Manager构造器在第一时间必须调用Employee的构造器,接下来才对子类独有的作用域进行初始化。
*/
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary(){
//这里就是通过super调用Employee类的getSalary()方法,获得基本工资
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b){
bonus = b;
}
}
运行结果
name=Car Cracker,salary=85000.0
name=Harry Hacker,salary=50000.0
name=Tommy Tester,salary=40000.0