多态参数

所谓的多态参数就是:方法的形参类型是父类,实参类型是子类(用父类的引用接收子类的对象)

 

测试类:

package PolyParameter;

//方法的形参类型是父类,实参类型是子类
public class PolyParameter01 {
    public static void main(String[] args) {
        PolyParameter01 p01 = new PolyParameter01();

        Empolyee empolyee = new Empolyee("员工一号",6000.45);
        p01.showEmpAnnual(empolyee);
        p01.testWork(empolyee);

        putong putong1 = new putong("普通员工一号",5000.01);
        p01.showEmpAnnual(putong1);
        p01.testWork(putong1);

        Manager m1 = new Manager("经理一号",10000.02,50000);
        p01.showEmpAnnual(m1);
        p01.testWork(m1);
    }
    //实现获取任何员工对象的年工资,并在 main 方法中调用该方法 [e.getAnnual()]
    public void showEmpAnnual(Empolyee e){
        System.out.println(e.getName()+"  的工资为  "+ e.GetAnnual());//动态绑定机制
    }

    //添加一个方法,testWork,如果是普通员工,则调用 work 方法,如果是经理,则调用 manage 方法
    public void testWork(Empolyee e){//形参用父类来接收,这样就可以把子类对象传给父类引用
        if (e instanceof Manager){
            ((Manager)e).manage();//向下转型
            //简便写法  e.  直接弹出
        }else if (e instanceof putong){
            ((putong)e).work();//向下转型(父类的引用强转成子类类型,然后调用子类的方法)
        }else{
            //nothing
        }
    }
}

父类:

package PolyParameter;

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;
    }
}

普通员工子类:

package PolyParameter;

public class putong extends Empolyee{

    public putong(String name, double salary) {
        super(name, salary);
    }

    //普通员工的特有方法
    public void work(){
        System.out.println("员工在工作");
    }

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

经理子类:

package PolyParameter;

public class Manager extends Empolyee{
    private double bonus;

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

    //经理的特有方法
    public void manage(){
        System.out.println("经理管理员工");
    }

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值