21-面向对象编程-多态参数

多态参数

方法定义的形参类型为父类类型,实参类型允许为子类类型

 

员工类(父类):

public class Empolyee {
    private String name;
    private double salary;
 
    public Empolyee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }
 
    //计算年工资的方法
    public double GetAnnual(){
        return 12*salary;
    }
}

普通员工类(子类):

public class Worker extends Employee {
    public Worker(String name, double salary) {
        super(name, salary);
    }

    //普通员工的特有方法
    public void work() {
        System.out.println("普通员工" + getName() + " is working!");
    }

    //员工的年薪,重写方法
    public double GetAnnual(){
        return super.GetAnnual();
    }
}

经理类(子类):

public class Manager extends Employee{
    //子类的特有属性,奖金
    private double bonus;

    public Manager(String name, double salary, double bonus) {
        super(name, salary);
        this.bonus = bonus;
    }

    public double getBonus() {
        return bonus;
    }

    public void setBonus(double bonus) {
        this.bonus = bonus;
    }

    //经理的特有方法
    public void manager() {
        System.out.println("经理" + getName() + " is managing!");
    }

    //经理的年薪,重写方法
    public double GetAnnual(){
        return super.GetAnnual() + bonus;
    }
}

测试类:

public class Test {
    public static void main(String[] args) {
        Worker w1 = new Worker("马铃薯", 3000);
        Manager m1 = new Manager("Smith", 5000, 10000);

        Test test = new Test();
        test.showEmpAnnual(w1);
        test.showEmpAnnual(m1);

        test.testWork(w1);
        test.testWork(m1);
    }

    //测试类中添加一个方法showEmpAnnual(Employee e),实现获取任何员工对象的年工资
    public void showEmpAnnual(Employee e) {
        System.out.println(e.getAnnual());
    }

    //测试类中增加一个方法testWork,如果是普通员工则调用work方法,如果是经理则调用manager方法
    public void testWork(Employee e) {
        if(e instanceof Worker) {
            //向下转型
            //Worker worker = (Worker) e;
            //worker.work();
            ((Worker) e).work();
        }else if(e instanceof Manager) {
            //向下转型
            //Manager manager = (Manager) e;
            //manager.manager();
            ((Manager) e).manager();
        }else {
            System.out.println("暂时不做处理");
        }
    }
}

 

posted @ 2023-09-05 09:46  马铃薯1  阅读(9)  评论(0编辑  收藏  举报