Java多态的应用练习题

  • 多态参数
    方法定义的形参类型为父类类型,实参类型允许为子类类型
  • 应用实列
    定义员工类Employee,包含姓名和月工资,以及计算年工资getAnnual的方法。普通员工类多了work方法,普通员工和经理分别要求重写getAnnual方法

     
  • 测试类中添加一个方法showEmpAnnal(Employee E),实现获取任何员工对象的年工资,并在main方法中调用该方法
  • 测试类中添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经理,则调用mange方法

 

package com.java.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;
    }
}

package com.java.poly_.polyparameter_;

public class Manage extends Employee {
    private double bones;

    public Manage(String name, double salary, double bones) {
        super(name, salary);
        this.bones = bones;
    }

    public double getBones() {
        return bones;
    }

    public void setBones(double bones) {
        this.bones = bones;
    }
    public void mana(){
        System.out.println("经理"+getName()+"正在管理...");
    }

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

 

package com.java.poly_.polyparameter_;

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

    @Override
    public double getAnnual() {//因为普通员工没有其他收入,则直接调用父类方法
        return super.getAnnual();
    }
}

 

package com.java.poly_.polyparameter_;

public class PolyParameter {
    public static void main(String[] args) {
        Work tom = new Work("tom", 2500);
        Manage milan = new Manage("milan", 5000, 200000);
        PolyParameter polyParameter = new PolyParameter();
        polyParameter.showEmpAnnual(tom);
        polyParameter.showEmpAnnual(milan);

        polyParameter.testWork(tom);
        polyParameter.testWork(milan);
    }
    public void showEmpAnnual(Employee e){
        System.out.println(e.getAnnual());
    }
    public void testWork(Employee e){
        if(e instanceof Work){
            ((Work) e).work();//向下转型操作
        }else if(e instanceof  Manage){
            ((Manage) e).mana();
        }else{
            System.out.println("不做处理");
        }
    }
}

 

 

你可能感兴趣的:(java,多态)