Answer the question
In order to leave comments, you need to log in
How to make a class hierarchy?
And to be precise. How to make the class hierarchy so that they can be accessed as generic. Now I will explain.
For example, we have the following hierarchy: Enemy -> Slug. The Enemy class has a Name property, and the Slug class, which inherits from the Enemy class, has both a Name property and a Health property. There is also a separate War class with the Battle method. The type of Enemy is passed to the Battle method, but the Enemy class does not have a Health property. Therein lies my question. How can I create a hierarchy so that instances can be treated as if they were shared?
Preferably without crutches and in detail, thanks in advance.
Here is the code:
class Program
{
static void Main()
{
var AnotherSlug = new Slug("common slug", 10);
War.Battle(AnotherSlug);
}
}
class War
{
static public void Battle(Enemy e)
{
Console.WriteLine(e.Name); // Нет ошибки
Console.WriteLine(e.HP); // Есть ошибка
}
}
class Enemy
{
public string Name { get; set; }
public Enemy(string name)
{
Name = name;
}
}
class Slug : Enemy
{
public int HP { get; set; }
public Slug(string name, int hp) : base(name)
{
HP = hp;
}
}
Answer the question
In order to leave comments, you need to log in
Raise the property to the parent class.
Make virtual methods on the parent bool Damage( int damagPoints ), bool Heal (int healthPoints).
Fix the invariants in the parent: there can be no negative health, no negative damage can be done, no negative healing can be done, there cannot be more than the maximum redistribution of the health jackal.
If you want to make some concrete Enemy with special properties, then make the implementations of the invariants also virtual. Let's say Slug takes 50% damage and only even damage.
Then for example Slug:
new public bool Damage( int damagePoints )
{
if (isDamageAcceptable(damagePoints))
{
int appliedDamage = Math.Ceiling(damagePoints/2);
TakeDamage(appliedDamage);
}
return isDamageAcceptable(damagePoints);
}
new protected bool isDamageAcceptable( int damagePoints) => (damagePoints > 0) && (0==damagePoints%2) );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question