继承(2)类的强制类型转换 instanceof

import java.util.*;
import java.time.*;

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 this.name;
    }
    
    public double getsalary()
    {
        return this.salary;
    }
    
    public LocalDate gethireday()
    {
        return this.hireday;
    }
    
    public void raisesalary(double byprecent)
    {
        double raise=salary*byprecent;
        salary=salary+raise;
    }
}

class Manager extends Employee{
    private double bonus;
    public Manager(String name,double salary,int year,int month,int day)
    {
        super(name,salary,year,month,day);
        this.bonus=0;
    }
    
    public double getsalary()
    {
        double basesalary=super.getsalary();
        return basesalary+bonus;
    }
    
    public void setbonus(double bonus)
    {
        this.bonus=bonus;
    }
}

public class Main{
    public static void main(String[] args)
    {
        var boss=new Manager("lol",10000,2021,4,9);
        boss.setbonus(100);
        var staff=new Employee[3];
        staff[0]=boss;
        staff[1]=new Employee("xzry",200,2023,6,8);
        staff[2]=new Employee("cf",3000,1998,8,6);
        if(staff[1] instanceof Manager)
        {
            System.out.println("可以强制类型转换");
        }else{
            System.out.println("不可以强制类型转换");
        }
    }
}
```![在这里插入图片描述](https://www.icode9.com/i/ll/?i=0173cea27c894f4abfe3ad21e829a6f3.png#pic_center)


上一篇:2021-10-09 MySQL查询练习题


下一篇:2021-10-6 Java学习(接口)