栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java-面向对象中级-多态参数(案列)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java-面向对象中级-多态参数(案列)

多态参数(案列)


Employee parent class

package com.hspedu.poly_.polyparameter;

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

    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 setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

Worker subclass

package com.hspedu.poly_.polyparameter;

public class Worker extends Employee{
    public Worker(String name, double salary) {
        super(name, salary);
    }
    public void work(){
        System.out.println("普通员工 " + getName() +" 正在工作....");
    }

    @Override
    public double getAnnual() {//无额外收入,则直接调用
        return super.getAnnual();
    }
}

Manager subclass

package com.hspedu.poly_.polyparameter;

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 manage(){
        System.out.println("经理 " + getName() + " 正在管理....");
    }

    //重写获取年薪的方法
    @Override
    public double getAnnual() {//额外加上奖金
        return super.getAnnual() + bonus;
    }
}

Polyparameter main class

package com.hspedu.poly_.polyparameter;

public class Polyparameter {
    public static void main(String[] args) {
        Worker tom = new Worker("tom", 2500);
        Manager milan = new Manager("milan", 5000, 200000);
        Polyparameter polyparameter = new Polyparameter();
        polyparameter.showEmpAnnual(tom);
        polyparameter.showEmpAnnual(milan);

        polyparameter.testWork(tom);
        polyparameter.testWork(milan);
    }

    //showEmpAnnual(Employee e)
    public void showEmpAnnual(Employee e){
        System.out.println(e.getAnnual());
    }
    //添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经理,则调用manage方法
    public void testWork(Employee e){
        if (e instanceof Worker){
            ((Worker) e).work();//向下转型
        }else if(e instanceof Manager){
            ((Manager) e).manage();//向下转型
        }else{
            System.out.println("不做处理....");
        }
    }

}

operation result

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/711888.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号