Skip to content

多态参数


基本介绍

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

代码示例

java
// 父类
package polyparemeter;

public class employee {
    private String name;
    private double salary;

    //构造器
    public employee(){

    }

    public employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public double getannual(){
        return 12 * salary;
    }

    public String getName() {
        return name;
    }

    //多态参数的体现,可以接收子类对象

    //父类独有的方法,返回员工工资
    public void showannual(employee e){
        System.out.println(e);
        System.out.println(e.getannual());

        //增加判断调用独有的方法
        System.out.println("\n接着使用instanceof操作符判断,调用独有的方法");
        if(e instanceof manager){
            manager mag = (manager) e;
            mag.manage();
        }else if(e instanceof worker){
            worker wok = (worker) e;
            wok.work();
        }
    }
}

// 子类
package polyparemeter;

public class manager extends employee{
    private double bonus;

    //构造器
    public manager(String name, double salary, double bonus) {
        super(name, salary);
        this.bonus = bonus;
    }

    // manage类独有的方法manage()
    public void manage(){
        System.out.println("经理 "  + getName() + " is managing");
    }

    //重写父类的getannual()方法
    public double getannual(){
        return super.getannual() + bonus;
    }
}

package polyparemeter;

public class worker extends employee {
    public worker(String name, double salary) {
        super(name, salary);
    }

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

}

// 主类
package polyparemeter;

public class main {
    public static void main(String[] args) {
        worker tom = new worker("tom",2500);
        manager smith = new manager("smith",2500,5000);
        employee e = new employee();
        e.showannual(tom);
        System.out.println("==============================");
        e.showannual(smith);
    }
}

// 运行结果
polyparemeter.worker@4554617c
30000.0

接着使用instanceof操作符判断,调用独有的方法
普通员工 tom is working
==============================
polyparemeter.manager@74a14482
35000.0

接着使用instanceof操作符判断,调用独有的方法
经理 smith is managin

代码分析

(1)创建了父类 employee,两个子类 manager 和 worker 继承父类

(2)重写 getannual()方法,目的是获取每个员工的薪资,在 employee 类中创建 showannual()方法,通过父类的形参接受子类的实参,体现多态参数的应用

(3)最后使用 instanceof 操作符,实现调用两个子类中特有的方法