Virtual Method
in C# object, we learned that inheritance can be used to create a relationship between two types. For example, map location is type of point.
Object often shares many atributes and behaviors as other type of objects.
Like animal type, all animals have same behaviors (they can move), but vertebrate and invertebrate have different attributes (backbone). Then, for the same vertebrate they move differently (gorilla and bird). In OOP, we also need the ability for objects to behave differently based on the type of object that they are. This is called polymorphism.
Let's go to code. Create another class, name it with ShieldedInvader class.
It will inherit from Invader class and let's create the constructor in it.
class ShieldedInvader : Invader
{
public ShieldedInvader(Path path) : base(path)
{ }
}
Up to this code, ShieldedInvader will behave in the same way like Invader class. That's because it inhertis all of the attributes and behavior from invader.
Let's make behavior so it won't sustain any damage when it being hit. For that, we need to change way of decreasing health method only for this type of invader.
Here is the example of polymorphism, same type (Invader) but have difference behavior (decreased Health).
First, we can make it possible to subclasses to provide their own implementation of decreased health by adding the keyword virtual to the method here.
// in invader class
public virtual void decreaseHealth(int factor)
{
Health -= factor;
}
Copy this code to ShieldedInvader class.
public static Random _random = new Random();
public override void decreaseHealth(int factor)
{
if (_random.NextDouble() > 0.5)
base.decreaseHealth(factor);
}
Mention the override attribute and base. Base will call the normal method of decreasing health in invader class.
Now, we have two types of decreasing health. So, we have to specify which one we want to call.
new ShieldedInvader(path),
new Invader(path),
new Invader(path),
new Invader(path)
We just have to change Invader to ShieldedInvader in Main class and everything works fine.