The Beauty Of Inherited Abstract Classes
- Sage Dupuy
- May 3, 2020
- 2 min read
Now apart from that absolutely incredible and enthralling title that just makes you wanna read more! This is gonna get a little bit technical, so bear with me. A magnificent thing in programming called an abstract class exists and it's magnificent as I mentioned. Abstract classes purpose is to avoid repetitive code and give the programmer the ability to remove very similar coding. I'll give you an example so it's better understood. We have 3 different types of enemies. The Ranger, the Fighter, and the Mage. All of them have 100 health and each of them have a unique name. The Ranger shoots arrows, The Fighter has to get close to kick, and the Mage heals it's companions. We could easily have different objects that hold all that information pretty easily like so:
class Fighter
{
int myFighterHealth = 100;
string myFighterName = "Qevin";
void KickMyOpponent();
}
class Mage
{
int myMageHealth = 100;
string myMageName = "Jort";
void HealMyCompanions();
}
class Ranger
{
int myRangerHealth = 100;
string myRangerName = "Timbert";
void ShootArrowsAtPlayer();
}It really doesn't take a genius to tell you that there is a LOT that's similar between those enemies. That's where abstract classes come in! We can notice that all the enemies have 3 things in common: A health value, a name and an action that they perform. We can make a new abstract class that holds all this for us. Then we'll create 3 separate classes that inherit those properties.
abstract class Enemy
{
int myHealth = 100; //The health value for this enemy
string myName = ""; //The empty name value for this enemy
abstract void MyEnemyAction(); //A function that can be overriden for each subclass to fit it's needs.
}
class Fighter : Enemy // The colon signifies that the Fighter class is inheriting from the Enemy class
{
override void MyEnemyAction()
{
KickThePlayer();
}
//... we'll assume that we set the enemies names and health to the appropriate values later on in each class.
}
class Mage : Enemy
{
override void MyEnemyAction()
{
HealMyCompanions();
}
}
class Ranger : Enemy
{
override void MyEnemyAction()
{
ShootArrowsAtPlayer();
}
}Now there are some coding snippets and practices not show, but that's just for the ease of explanation. Now if we implement the functions we need we have 3 working enemies with entirely different names, possibly health values and actions. This reduces the code amount quite a bit and simplifies the structure of games a lot as well. I hope you have some understanding of how abstract classes work now. This is definitely not the only thing you need to understand it and it's something that you can takes some knowledge from.


Comments