Class
Stole this amazing explanation from iAmDev on YouTube. I would highly recommend their channel for new devs, especially this short playlist on OOP.
A class is a blueprint/template of the methods and variables in a particular object. You can use it to create many objects that inherit some of its properties.
You are trying to build a pirate ship for a video game and need to create a bunch of cannons with similar functionality.
class Cannon
{
public int damage;
private void Fire()
{
CreateCannonBall(damage)
ReloadAnimation();
}
private void CreateCannonBall()
{
//Generate a 3D ball and shoot it out, dealing damage
}
private void ReloadAnimation()
{
//Run reload animation
}
}
By using the Cannon
class above as a blueprint, we can now create a Cannon
object for a small and scrappy pirate ship:
class Scrappy
{
private Cannon mainCannon = new Cannon();
mainCannon.damage = 10;
mainCannon.Fire();
}
And, by using a list, we can add a dozen cannons for a massive pirate flagship:
class Flagship
{
private List<Cannon> cannons = new List<Cannon>();
foreach(var cannon in cannons)
{
cannon.damage = 20;
cannon.Fire();
}
}
Because you use the cannon class, you don't need to reimplement Fire()
or create a variable for damage
, it's all contained within the Cannon
class.