继承相同父级的两个对象具有交换属性

时间:2014-09-24 18:54:10

标签: java inheritance abstract-class

我目前正在编写一个模拟Java中大规模战斗的群体AI程序。我使用了一个抽象类AIUnit,定义如下:

public abstract class AIUnit
{
private int health;

protected AIUnit(int health)
{
    this.health = health;
}

public abstract void Move();    //Move unit
public abstract void Attack(AIUnit unit);   //Attack unit in front
public abstract void Send(int freq,int msg);    //Send message on frequency
public abstract void Recv();    //Receive message

public int GetHealth()
{
    return health;
}

public void TakeDamage(String name)
{
    --health;
    System.out.println(name+" took damage!  Health remaining: "+health);
    if (health == 0)
    {
        System.out.println(name+" is dead!");
        this.Die();
    }
}

public void Die()
{
    System.exit(0);
}
}

目前还有两个AI类:Barbarian和Medic,定义如下: 夷:

public class Barbarian extends AIUnit
{   
private String name = "Barbarian";
public Barbarian(int health)
{
    super(health);
}
//Move unit
public void Move()
{
}
//Attack unit in front
public void Attack(AIUnit unit)
{
    unit.TakeDamage(name);
}
//Send message on frequency
public void Send(int freq, int msg)
{
}
//Receive message
public void Recv()
{
}
}

和Medic:

public class Medic extends AIUnit
{
private String name = "Medic";
public Medic(int health)
{
    super(health);
}
//Move unit
public void Move()
{
}
//Attack unit in front
public void Attack(AIUnit unit)
{
    unit.TakeDamage(name);
}
//Send message on frequency
public void Send(int freq, int msg)
{
}
//Receive message
public void Recv()
{
}
//Heal unit
public void Heal(AIUnit unit)
{
}
}

请注意,这两个类大多相同,只是名称不同,而且Medic类有一个未实现的Heal方法。

现在,在使用以下Main类测试一个简单的Attack方法时:

import java.util.Random;

public class Main
{
public static int barbhealth = 3;
public static int medhealth = 2;
public static void main(String[] args)
{
    Random rand = new Random();
    int whoAttacks = rand.nextInt() % 2;
    Barbarian b = new Barbarian(barbhealth);
    Medic m = new Medic(medhealth);
    for(;;whoAttacks = rand.nextInt() % 2)
    {
        if (whoAttacks == 0)
            m.Attack(b);
        else
            b.Attack(m);
    }
}
}

我得到奇怪的结果。出于某种原因,应该有3个健康的野蛮人从2开始,而应该有2个健康的医生从3开始。有人可以解释这种行为吗?

1 个答案:

答案 0 :(得分:5)

您打印的名称错误。给定

m.Attack(b);

//Attack unit in front
public void Attack(AIUnit unit)
{
    unit.TakeDamage(name);
}

public void TakeDamage(String name)
{
    --health;
    System.out.println(name+" took damage!  Health remaining: "+health);
    if (health == 0)
    {
        System.out.println(name+" is dead!");
        this.Die();
    }
}

thisMedic。因此unitBarbarianname"Medic"。因此Medic看起来Barbarian正在受到伤害{{1}}。