public abstract class Character
{
protected Weapon weapon;
public string Name;
public int Health = 10;
public int Strength;
public Character()
{
}
public void Attack()
{
weapon.useweapon();
}
}
public class Warrior : Character
{
public Warrior()
{
weapon = new Sword();
Health = 10;
Strength = 25;
}
public void SetWeapon(Weapon newweapon)
{
weapon = newweapon;
}
}
public class Wizard : Character
{
public Wizard()
{
weapon = new Spell();
Health = 15;
Strength = 10;
}
}
如您所见,有一个抽象 Character 类和两个 Character 子类。在这个程序中,只有战士可以更换武器。现在,我不想讨论代码本身,我想知道的是,在我的实现代码中为什么要使用它:
Character Zizo = new Warrior();
Character Hang = new Wizard();
代替 -
Warrior Zizo = new Warrior();
Wizard Hang = new Wizard();
Zizo.SetWeapon(new Axe()); //I can only use this method in this implementation
两者有什么区别,通过抽象类声明对象有什么好处?