Use Abstract class or Interface?
When starting out, it is difficult to understand when to use an abstract class or an interface. This blog is mean to help you understand it.
In programming, it is really important to implement good coding practices like OOP inheritance, using abstract classes and interfaces. Here is a very brief summary on both topics. Further information can be found on internet.
Abstract class
It declares fields, properties and methods that can be used for any class that inherits from it. The method implementation can be abstract (mandatory) or virtual (optional)
Interfaces
It declares methods, properties and events.
It is a contract, so each class that inherits from it must implement its declared members.
So, when to use Abstract class or Interface?
Abstract classes: when creating several objects of the same type
For example: soccerball, cricketball and basketball are all balls. So it makes sense to create a base class called ball
Interfaces: several types of objects behave the same way
A player and an enemy can move, shoot and take damage, so they can implementIMove
, IShoot
and IDamage
Implementing this simple UML diagram
The pics: read from top to bottom and then vice versa
The process:
DamageOnClick
- When click on screen, if hit on
Car1
orBarrel1
, it will try to executeTakeDamage(1)
Case 1: Barrel1
DamageOnClick
will look forITakeDamage
inBarrel1
script- As it inherits from
BaseDamage
and it inheritsITakeDamage
as well, the conditionif(iDamage != null)
inDamageOnClick
istrue
TakeDamage()
will be executed with a value of1
in accordance with parent’sITakeDamage
implementation- The
maxHealth
value must be set in inspector
Case 2: Car1
- First 3 steps as previously
TakeDamage()
will be executed with a value of3
becauseCar1
overrides its parent’s value.- The
maxHealth
is set with hardcode when overridingSetMaxHealth()
Why are abstract classes and interfaces important?
Without interfaces, when click on the GameObject, the code will look some like this:
The developer would have to evaluate each possible GameObject that could be hit when click on screen.
In this case there are only 2 GameObjects, but imagine if they would be 30 or 100 hundred types of enemies…
On the other hand, when using interfaces
The code is shorter, cleaner, and most importantly, the if
condition will check the implementation of TakeDamage()
on the object that has been hit through the ITakeDamage
implementation. That’s all.
The developer doesn’t need to explicitly code every possible case where a GameObject can be hit.
For example, if I have 20 different types of enemies, each one must to implement the TakeDamage()
method, and those 2 lines of code will be enough to execute it, no matter the type of enemy.