Role类:
package org.jsoft.lianxi;
public abstract class Role {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
abstract public int attack();
}
Magicer类:
package org.jsoft.lianxi;
public class Magicer extends Role {
private int level;
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public Magicer(int level){
this.level=level;
}
public int attack(){
return getLevel()*5;
}
}
Soldier类:
package org.jsoft.lianxi;
public class Soldier extends Role{
private int hurt;
public int getHurt() {
return hurt;
}
public void setHurt(int hurt) {
this.hurt = hurt;
}
public Soldier(int hurt){
this.hurt=hurt;
}
public int attack(){
return getHurt();
}
}
Team类:
package org.jsoft.lianxi;
public class Team {
private Role [] role;
public Role[] getRole() {
return role;
}
public void setRole(Role[] role) {
this.role = role;
}
public void setRole(int i){
if(i<=6&&i>=0){
this.role=new Role[i];
}
else{
System.out.println("队伍成员人数要在6人以内!");
}
}
public void addMember(Role role){
for(int i=0;i<getRole().length;i++){
if(getRole()[i]==null){
getRole()[i]=role;
break;
}
}
}
public int attackSum(){
int sum=0,n=0;
for(int i=0;i<getRole().length;i++){
if(getRole()[i]!=null) n++;
}
for(int i=0;i<n;i++){
System.out.println(getRole()[i].getName()+"的伤害为:"+getRole()[i].attack());
sum += getRole()[i].attack();
}
return sum;
}
}
TestRole类:
package org.jsoft.lianxi;
public class TestRole {
public static void main(String[] args) {
Role r1=new Magicer(8);
r1.setName("法师1");
Role r2=new Soldier(20);
r2.setName("战士1");
Team t=new Team();
t.setRole(2);
t.addMember(r1);
t.addMember(r2);
System.out.println("总伤害为:"+t.attackSum());
}
}