Java:实现多子类与父类的继承,并实现各自类的方法(第九周)

题目来源:大工慕课 链接
作者:Caleb Sung

题目要求

  1. 阅读幻灯片中关于PersonEmployeeManager的源代码;
  2. 实现UML类图中所示的三个类:
    这里写图片描述

  3. AthletegetDescription()方法应该返回一个字符串,例如An Athlete XXXName with height of XXX and weight of XXX

  4. BasketballPlayer中的getDescription()应该返回一个字符串,例如A basketball player XXXName with shooting level of XXX
  5. BaseballPlayer中的getDescription()应该返回一个字符串,例如A baseball player XXXName with hitting level of XXX
  6. 在主要功能中,实现一个由3名运动员组成的阵列,并分别与AthleteBasketballPlayerBaseballPlayer一起填充阵列。 然后,使用循环打印阵列中所有运动员的描述信息。

参考代码

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值