Java基础知识:继承(1)

设置一个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的一个实例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值