Java之多态参数

用处

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

举个例子吧

public void test(Person a){
a.work()
}//test(b)b为Person的子类即可

面对一些调用子类特有的要求
可以用if(instanceof)
来判断以后向下转型后调用
比如下面的testwork

题目

在这里插入图片描述

啊啊啊,我自己写出来了,一定要好好看看,我自我感觉结合的知识挺好,也理解了构造器的重大作用
一个个赋值真的麻烦啊

父类员工

package com.hansp.poly.polypar;

public class Employee {
    private String name;
    private int salary;

    public Employee(String name, int salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
    public int getAnnual(){
        return salary*12;
    }
}

子类经理

package com.hansp.poly.polypar;

public class manager extends Employee {
    private int bonus;

    public manager(String name, int salary, int bonus) {
        super(name, salary);
        this.bonus = bonus;
    }

    public void manage(){
        System.out.println("经理管事");
    }

    public int getBonus() {
        return bonus;
    }

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

    @Override
    public int getAnnual() {
        return super.getAnnual()+getBonus();
    }
}

子类员工

package com.hansp.poly.polypar;

public class staff extends Employee {
    public void work(){
        System.out.println("员工工作");

    }

    public staff(String name, int salary) {
        super(name, salary);
    }

    @Override
    public int getAnnual() {
        return super.getAnnual();
    }
}

测试类

package com.hansp.poly.polypar;

public class Demo {
    public static void main(String[] args) {

        manager a = new manager("小王", 8000, 2000);
        staff b = new staff("小袁", 5000);
        Demo c=new Demo();
        c.show(a);
        c.show(b);
        c.testWork(a);
        c.testWork(b);

    }
    public  void show(Employee e)//展现员工的年工资
    {
        System.out.println(e.getAnnual());

    }
    public void testWork(Employee e){
        if(e instanceof manager)
        {
            manager a=(manager) e;
            a.manage();
        }
        if(e instanceof staff){
            staff a=(staff) e;
            a.work();
        }

    }
}

运行结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小袁拒绝摆烂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值