Why declare an object as its inherited abstract class instead of its own class

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;
    }
}

As you can see, there is an abstract class Character and two subclasses Character. In this program, only a warrior can change weapons. Now I'm not going to discuss the code itself, what I want to know in my implementation code is why I should use this:

Character Zizo = new Warrior();
Character Hang = new Wizard();

Instead

Warrior Zizo = new Warrior();
Wizard Hang = new Wizard();
Zizo.SetWeapon(new Axe()); //I can only use this method in this implementation

What is the difference between the two and what advantage do I get by declaring an object an abstract class?

+3
source share
6 answers

. , . , - Attack(), , , (, Warrior, Wizard ..) , abstract Character.

, .

+4

, , , Character , , .

:

public void AttackAndHeal(Character character)
{
    character.Attack();
    character.Health++;
}

Warrior zizo = new Warrior();
Wizard hang = new Wizard();

AttackAndHeal(zizo);
AttackAndHeal(hang);
+3

, , . , .

, - H- . , () , Kill , .

+1

Warrior Wizard Character

var characters = new List<Character>();
characters.Add(new Warrior());
characters.Add(new Wizard());
foreach (var c in characters)
{
    //use members exposed by c
}
+1

Zizo Character, Character Zizo. , , Character. - Zizo, Warrior, .

0

(.. ) , , . , , . , , "" ( ), , , - , .

0

All Articles