Home > Enterprise >  How change object type, when child inherit from same parent but have difrrent method and props
How change object type, when child inherit from same parent but have difrrent method and props

Time:12-12

In college I got task to do. I have simple program like below. I have one parent class who represent person, and few child which inherit from it and represent role(Archer, Knight, Wizzard). I must implemented funcionality to easy switching object type, from Archer to Knight and so on. At first I thought about creating a large interface with all the unique methods, but it breaks the SOLID rule, but I can't break this rule. Could someone help figure it out?

This is how look code:

public abstract class Person
    {
        public String Name;
        
        public char Age;
        
        void describe()
        {
            //some code
        }
    }

Role class:

public class Archer : Person
    {
        public int agility;

        public void describe()
        {
            //some code
        }

        public void fightUsingBow()
        {
            //some code
        }
    }

Next role:

class Wizzard : Person
    {
        public int mana;

        public void describe()
        {
            //some code
        }
        
        public void castASpell()
        {
            //some code
        }
    }

CodePudding user response:

Do you really need to change the object type? You can abstract this method too

For example: Change FightUsingBow() CastASpell() to Attack() or SpecialAttack()

You can create an abstract class for them if you want. For example Guardian with parent class Person

abstract class Guardian : Person
{
    public abstract void Attack();
}

Use Guardian class for your guardians.

CodePudding user response:

You can't just "switch" an archer to a knight. An archer is not a knight. You could create a new knight using the same base properties of the archer, but there's no built-in way to do that. One way is to use a "copy constructor" for a person - something like:

public Person(Person basePerson)
{
    this.Name = basePerson.Name;
    this.Age = basePerson.Age
}

then add a constructor to Knight that calls the copy constructor:

public Knight(Person basePerson) : base(basePerson) {}
  • Related