面向对象高级:游戏团队角色扮演 Role角色类是所有职业的父类,包含受保护的属性:roleName(角色名字),public int getAttack()(返回角色的攻击力,不能确定)。 Master法师类继承了Role类,包含属性:name(姓名),grade(魔法等级1~ 10),public int getAttack()(法师攻击力=魔法等级*5)。 Soldier战士类继承了Role类,包含属性:name(姓名),attack(攻击力);public int attack()方法(返回战士的攻击力),Soldier类的所有属性都应当作为私有,并提供相应的getter/setter方法。 Team 团队类,一个团队包括一个法师、若干个战士(最多6个,用Soldier[]实现)、战士实际个数(num)。定义了两个方法:public boolean addMember(Solider s)方法(当战士实际个数不超过6时,将s赋值给第num个数组元素), public int attackSum()方法(返回该团队的总攻击力)。 根据以上描述,创建相应的类。并编写相应的测试代码。
时间: 2024-04-28 07:19:33 浏览: 99
面向对象编程的高级概念
以下是对应的Java代码:
```
public class Role {
protected String roleName;
public int getAttack() {
return 0;
}
}
public class Master extends Role {
private String name;
private int grade;
public Master(String name, int grade) {
this.name = name;
this.grade = grade;
}
public int getAttack() {
return grade * 5;
}
}
public class Soldier extends Role {
private String name;
private int attack;
public Soldier(String name, int attack) {
this.name = name;
this.attack = attack;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
}
public class Team {
private Master master;
private Soldier[] soldiers;
private int num = 0;
public Team(Master master, Soldier[] soldiers) {
this.master = master;
this.soldiers = soldiers;
num = soldiers.length;
}
public boolean addMember(Soldier s) {
if (num < 6) {
soldiers[num++] = s;
return true;
}
return false;
}
public int attackSum() {
int sum = 0;
sum += master.getAttack();
for (int i = 0; i < num; i++) {
sum += soldiers[i].getAttack();
}
return sum;
}
}
public class Test {
public static void main(String[] args) {
Master master = new Master("张三", 10);
Soldier s1 = new Soldier("李四", 20);
Soldier s2 = new Soldier("王五", 30);
Soldier[] soldiers = {s1, s2};
Team team = new Team(master, soldiers);
Soldier s3 = new Soldier("赵六", 40);
if (team.addMember(s3)) {
System.out.println("成功添加新成员");
} else {
System.out.println("添加新成员失败");
}
System.out.println("团队总攻击力为:" + team.attackSum());
}
}
```
运行结果为:
```
成功添加新成员
团队总攻击力为:220
```
其中,Master类和Soldier类都继承了Role类,并分别实现了getAttack()方法,同时Soldier类还提供了私有属性attack和相应的getter/setter方法。Team类包含一个Master对象和一个Soldier数组,并实现了addMember()和attackSum()方法。在测试代码中,我们创建了一个Master对象和两个Soldier对象,将它们作为参数传入Team对象的构造方法中,然后再添加一个新的Soldier对象,最后输出团队的总攻击力。
阅读全文