下面是由继承Employee 类来定义Manager 类的格式, 关键字extends 表示继承。
public class Manager extends Employee
{
添加方法和域
}
子类中继承父类的域和方法;
覆盖方法
父类的方法,并不适用于子类的时候,需要提供一个新的方法来覆盖父类中的这个方法
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
子类构造器
public Manger(String name, double salary, int year, int month, int day)
{
super(name, salary, year, month, day);
bonus = 0;
}
因为子类终的构造器不能直接访问父类的私有域,所以必须利用父类的构造器对这部分私有域进行初始化,可以使用super实现对父类构造器的调用。使用super调用构造器的语句必须是子类构造器的第一条语句。
package testbotoo; import java.time.LocalDate; public class Employee { private String name; private double salary; private LocalDate hireDay; public Employee(String name, double salary, int year, int month, int day) { this.name = name; this.salary = salary; hireDay = LocalDate.of(year, month, day); } public String getName() { return name; } public double getSalary() { return salary; } }
package testbotoo; public class Manager extends Employee { private double bonus; /** * @param name the employee‘s name * @param salary the salary * @param year the hire year * @param month the dire onth * @param day the hire day */ public Manager(String name, double salary, int year, int month, int day) { super(name, salary, year, month, day); bonus = 0; } public double getSalary() { double baseSalary = super.getSalary(); return baseSalary +bonus; } public void setBonus(double b) { bonus = b; } }
package testbotoo; public class ManagerTest { public static void main(String[] args) { Manager boss = new Manager("aaa",8000,1999,12,20); boss.setBonus(5000); Employee[] staff = new Employee[3]; staff[0] = boss; staff[1] = new Employee("hary",5000,1989,3,15); staff[2] = new Employee("mayun",50000,1989,3,16); for (Employee e : staff) System.out.println("name="+e.getName()+",salary="+e.getSalary()); } }