版权声明:根据《中华人民共和国著作权法》,如需转载请标明来源并联系作者进行授权。本文作者保留依法追究未经授权转载等侵犯作者著作权等的违法行为之权利。 https://blog.csdn.net/qq_41933331/article/details/81976939
题目来源:大工慕课 链接
作者:Caleb Sung
题目要求
- 阅读幻灯片中关于Person,Employee和Manager的源代码;
实现UML类图中所示的三个类:
Athlete的
getDescription()
方法应该返回一个字符串,例如An Athlete XXXName with height of XXX and weight of XXX
;- BasketballPlayer中的
getDescription()
应该返回一个字符串,例如A basketball player XXXName with shooting level of XXX
; - BaseballPlayer中的
getDescription()
应该返回一个字符串,例如A baseball player XXXName with hitting level of XXX
; - 在主要功能中,实现一个由3名运动员组成的阵列,并分别与
Athlete
,BasketballPlayer
和BaseballPlayer
一起填充阵列。 然后,使用循环打印阵列中所有运动员的描述信息。
参考代码
Athlete类(父类)
class Athlete{
private String name;
private int height;
private int weight;
public Athlete(String n, int h, int w){
name = n;
height = h;
weight = w;
}
public String getName(){
return name;
}
public String getDescription() {
return "An Athlete "+ name + " with height of "+ height +" and weight of "+ weight + ".";
}
}
BasketballPlayer类(子类1)
class BasketballPlayer extends Athlete{
private int shootLv;
public BasketballPlayer(String n, int h, int w, int sl) {
super(n, h, w);
shootLv = sl;
}
public String getDescription() {
return "A basketball player "+ getName() +" with shooting level of "+ shootLv + ".";
}
}
BaseballPlayer类(子类2)
class BaseballPlayer extends Athlete{
private int hitLv;
public BaseballPlayer(String n, int h, int w, int hl) {
super(n, h, w);
hitLv = hl;
}
public String getDescription() {
return "A baseball player "+ getName() +" with hitting level of "+ hitLv + ".";
}
}
主函数与测试用例
public class AthletesTset {
public static void main(String[] args) {
//Tests
Athlete [] athletes = new Athlete[3];
athletes[0] = new Athlete("Bob", 188, 75);
athletes[1] = new BasketballPlayer("Sam", 190, 80, 6);
athletes[2] = new BaseballPlayer("Tom", 179, 69, 8);
for(Athlete a : athletes) {
System.out.println(a.getDescription());
}
}
}
运行结果
An Athlete Bob with height of 188 and weight of 75.
A basketball player Sam with shooting level of 6.
A baseball player Tom with hitting level of 8.