设置一个Employee类:
import java.time.*;
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;
this.hireDay = LocalDate.of(year, month, day);
}
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public LocalDate getHireDay(){
return hireDay;
}
public void raiseSalary(int bypercent){
double raise = salary * bypercent / 100;
salary += raise;
}
}
再从Employee中挑选Manager,故Manager继承Employee:
public class Manager extends Employee{
private double bonus;
/**
* name
* salary
* hire year
* hire month
* hire day
*/
public Manager(String name, double salary, int year, int month, int day){
super(name, salary, year, month, day);
bonus = 0;
}
public void setBonus(double bonus){
this.bonus = bonus;
}
public double getSalary(){
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
}
如果在Test程序中输入
Manager boss = (Manager) staff[1];
运行这个程序时,Java运行时系统会报错,产生一个ClassCastException异常。
Test代码:
public class ManagerTest{
public static void main(String[] args) {
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", 35.0, 2007, 7, 4);
staff[2] = new Employee("Renyaoyao", 30.0, 2017, 12, 3);
//Manager boss1 = (Manager)staff[1];
//boss1.setBonus(5000);
if (boss instanceof Employee){
System.out.println("1");
}
else{
System.out.println("0");
}
}
}
显然,Manager的一个实例boss也是其父类Employee的一个实例。