Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare an object by 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 Character class and two Character subclasses. In this program, only the warrior can change weapon. Now, I'm not looking to discuss the code itself, what I want to know is, in my implementation code why would I use this:

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

Instead of -

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 benefit do I get by declaring the object by the abstract class?

like image 999
aelsheikh Avatar asked Jan 18 '26 21:01

aelsheikh


1 Answers

Client code should use the minimally required interface or abstract class definition. You do this primarily to keep code more loosely-coupled. In your example, if the calling code only ever needed to Attack() but is not concerned with how that's carried out, implemented, or what particular type (e.g. Warrior, Wizard, etc) is doing the attacking then it should use the abstract Character class.

When it necessarily must have knowledge of a particular implementation or concrete class, then it is appropriate to explicitly make use of one.

like image 89
Yuck Avatar answered Jan 21 '26 12:01

Yuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!