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

Java练习(三十一)---多态参数练习

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

Java练习(三十一)---多态参数练习

题目:
Employee员工类中有姓名和月工资的属性(private),还有计算年工资的getAnnual方法;
普通员工类中有work方法,继承Employee类;
经理类有bouns奖金属性和manage管理方法,也继承Employee类;
普通员工类和经理类都重写父类的getAnnual方法;
测试类中添加一个方法show(Employee e),实现获取员工对象年工资,并在main方法中调用该方法;
在测试类中创建一个testwork方法,如果是普通员工调用work,如果是经理,调用manage方法;
解答:
父类

package polyarr;

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

    public Employee(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 getSalary()*12;
    }
}

子类

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

    public void work() {
        System.out.println( "普通员工" + getName() + "在工作");

    }

    @Override
    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 void manage() {
        System.out.println( "经理" + getName() + "在演讲");

    }

    public double getBonus() {
        return bonus;
    }

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

    @Override
    public double getAnnual() {
        return super.getAnnual()+bonus;
    }
}

调用类

public class TestEM {
    public static void main(String[] args) {
        NormalEmployee normal = new NormalEmployee("", 1000);
        Manager manager = new Manager("lisi", 100, 30000);
        TestEM t = new TestEM();
        t.show(normal);
        t.show(manager);

        t.testwork(normal);
        t.testwork(manager);
    }

    public void show(Employee e) {
        System.out.println(e.getAnnual());
    }

    public void testwork(Employee e) {
        if (e instanceof NormalEmployee) {
            NormalEmployee n = (NormalEmployee) e;
            n.work();
        } else if (e instanceof Manager) {
            Manager m = (Manager) e;
            m.manage();
        } else {
            System.out.println("111");
        }
    }
}

输出结果:
12000.0
31200.0
普通员工在工作
经理lisi在演讲

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

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

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