目录
题目
父类:Employee类
package com.ploy_.polyparameter;
public class Employee {
private String name;
private double monthSalary;
public Employee(String name, double monthSalary) {
this.name = name;
this.monthSalary = monthSalary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMonthSalary() {
return monthSalary;
}
public void setMonthSalary(double monthSalary) {
this.monthSalary = monthSalary;
}
public double getAnnual(){
// System.out.println("1");
return 12*monthSalary;
}
}
子类:Worker
package com.ploy_.polyparameter;
public class Worker extends Employee{
public Worker(String name, double monthSalary) {
super(name, monthSalary);
}
public void work(){
System.out.println("普通员工 "+getName()+" is working");
}
@Override
public double getAnnual() {//因为普通员工无其它收入,则直接调用父类
System.out.println("Worker:");
return super.getAnnual();
}
}
子类:Manage
package com.ploy_.polyparameter;
public class Manage extends Employee{
private double bonus;
public Manage(String name, double monthSalary, double bonus) {
super(name, monthSalary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public void manage(){
System.out.println("经理 "+getName()+" is managing");
}
@Override
public double getAnnual() {
System.out.println("Manage:");
return super.getAnnual()+bonus;
}
}
主类
package com.ploy_.polyparameter;
//多态参数
//方法定义的形参类型为父类类型,实参类型允许为子类类型
//实例1:主人喂动物
//实例2:
//定义员工类Employee,包含了姓名和月工资,以及计算年工资getAnnial的方法
//普通员工和经理继承了员工,经理类多了奖金bonus属性和管理manage方法,
//普通员工累多了work方法,普通员工和经理类要求分别重写getAnnual方法
//测试类中添加一个方法showEmpAnnal(Employee e),实现获取任何员工对象的年工资,并在main方法中调用该方法(e.getAnnual())
//测试类中添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经理,则调用manage方法
public class PolyParameter {
public static void main(String[] args) {
Employee[] employes = new Employee[2];
employes[0] = new Worker("jack", 2500);
employes[1] = new Manage("jin", 5000, 20000);
PolyParameter p = new PolyParameter();
p.showEmpAnnal(employes[0]);
p.showEmpAnnal(employes[1]);
p.testWork(employes[0]);
p.testWork(employes[1]);
}
public void showEmpAnnal(Employee e){
System.out.println(e.getAnnual());//动态绑定机制
}
public void testWork(Employee e){
if(e instanceof Worker){
Worker w=(Worker) e;
w.work();
}
if(e instanceof Manage){
((Manage) e).manage();
}
}
}