多态参数:练手小题
- 1. 前言:
- 2. 分析需求:
- 2.1 主类Employee分析
- 2.1.1 主类Employee代码片段
- 2.2 子类work普通员工分析
- 2.2.1 子类work普通员工代码片段
- 2.3 子类manage经理分析
- 3. 回到主文件:
- 3.1 主文件代码实现:
- 4. 效果显示:
- 5. 写在最后:
1. 前言:
父类Employee员工类含有普通worker员工和manage经理两个子类,其中主类有姓名、月工资salary;主类还有不同子类含有不同的工作模式:普通员工有work方法,经理有特有属性年终奖 bonus,和manage方法;现要求在主文件中设计能调用所有类的getAnnual()年薪方法和textwork()工作方法
2. 分析需求:
2.1 主类Employee分析
父类Employee员工类有姓名、月工资salary
以及获取年薪方法getAnnual;
2.1.1 主类Employee代码片段
package com.polyparamenter_;
public class Empolyee {
private String name;
private double salary;
public Empolyee(String name, double salary) {
this.name = name;
this.salary = salary;
}
//得到年度工资方法;salary * 12;
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;
}
}
2.2 子类work普通员工分析
没有特有属性,仅有工作模式方法work();
2.2.1 子类work普通员工代码片段
package com.polyparamenter_;
public class worker extends Empolyee {
public worker(String name, double salary) {
super(name, salary);
}
public void work() {
System.out.println("普通员工 " + getName() + " 正在工作中...");
}
public double getAnnual() {
return super.getAnnual();
}
}
2.3 子类manage经理分析
子类manage经理具有特有属性private double bonus;
以及工作模式manage管理;
package com.polyparamenter_;
public class manager extends Empolyee {
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 getAnnual() { //重写获取年薪
return super.getAnnual() + bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
}
3. 回到主文件:
主文件现要求设计能调用所有类的getAnnual()年薪方法和textwork()工作模式方法
在主文件中写入showEmpolyee:
public void showEmpolyee(Empolyee e)方法实现对所有的对象能调取年薪,并在main函数中调用;
textWork
public void textWork(Empolyee e)方法,对应不同员工调用特有方法普通员工调用Work,经理调用manage;
3.1 主文件代码实现:
package com.polyparamenter_;
import javafx.concurrent.Worker;
public class PloyParamenter {
public static void main(String[] args) {
worker tom = new worker("Tom", 3000);
manager milan = new manager("milan", 5000, 20000);
PloyParamenter ployParamenter = new PloyParamenter();
ployParamenter.showEmpolyee(tom);
ployParamenter.showEmpolyee(milan);
ployParamenter.textWork(tom);
ployParamenter.textWork(milan);
}
//在主文件中写入一个方法实现对所有的对象能调取年薪,并在main函数中调用;
public void showEmpolyee(Empolyee e) { // 动态绑定机制
System.out.println(e.getName() + "年薪为:" +e.getAnnual());
}
//textWork方法,对应不同员工调用特有方法普通员工调用Work,经理调用manage;
public void textWork(Empolyee e) {
if(e instanceof worker){
((worker) e).work();
}else if(e instanceof manager){
((manager) e).manage();
}else{
System.out.println("职位不清,不做处理...");
}
}
}
4. 效果显示:
5. 写在最后:
这一小题主要考到在main中设计方法调用所有类的特有方法;
showEmpolyee(Empolyee e)//多态参数
textWork(Empolyee e) //多态参数
这两个方法具体实现请看代码;
蟹蟹 阅读 ^ - ^