面向对象编程-多态参数(练习)
- 定义员工类Employee,包含姓名和月工资【private】,以及计算年工资getAnnual的方法。普通员工和经理继承了员工,经理类多了奖金bonus属性和管理manage方法,普通员工类多了work方法,普通员工和经理类要求分别重写getAnnual方法
- 测试类中添加一个方法showEmpAnnal(Employee e),实现获取任何员工对象的年工资,并在main方法中调用该方法(e.getAnnual())
- 测试类中添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经理,则调用manage方法
先用前面所学知识做一遍(多态数组)
下面改为【多态参数】实现
package com.tao.polymorphic_.polyparameter_;
/**
* Create By 刘鸿涛
* 2021/12/18 8:42
*/
public class Employee {
private String name;
private int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
//得到年工资的方法,返回double
public double getAnnual(){
return 12 * salary;
}
}
package com.tao.polymorphic_.polyparameter_;
/**
* Create By 刘鸿涛
* 2021/12/18 8:59
*/
public class Manager extends Employee{
private double bonus;
public Manager(String name, int salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public double getAnnual(){
System.out.print(super.getName() + "经理的薪资为:");
return super.getAnnual() + bonus;
}
public void manager(){
System.out.println(super.getName() + ":经理在管理员工...");
}
}
package com.tao.polymorphic_.polyparameter_;
/**
* Create By 刘鸿涛
* 2021/12/18 8:48
*/
public class Worker extends Employee{
public Worker(String name, int salary) {
super(name, salary);
}
public void work(){
System.out.println(super.getName() + ":工人在工作....");
}
public double getAnnual(){
System.out.print (super.getName() + "工人的薪资为:");
return super.getAnnual();
}
}
package com.tao.polymorphic_.polyparameter_;
/**
* Create By 刘鸿涛
* 2021/12/18 9:04
*/
public class Test {
public static void main(String[] args) {
Worker tom = new Worker("tom", 4000);
Manager milan = new Manager("milan", 5000, 20000);
Test test = new Test();
test.showEmpAnnual(tom);
test.showEmpAnnual(milan);
test.testWork(tom);
test.testWork(milan);
}
//showEmpAnnual(Employee e)
//实现获取任何员工对象的年工资,并在main方法中调用该方法【e.getAnnual】
public void showEmpAnnual(Employee e){
System.out.println(e.getAnnual()); //动态绑定机制
}
public void testWork(Employee e){
if(e instanceof Worker){
((Worker)e).work(); //有向下转型操作
}else if(e instanceof Manager){
((Manager)e).manager(); //有向下转型操作
}else{
System.out.println("不作处理....");
}
}
}