Inheritance ๐Ÿงฌ

Learn How Classes Can Be Family! (It's Easier Than You Think!)

Beginner Friendly 25 min read Lesson 6 of 11

Hey there, Future C# Master! ๐Ÿ‘‹

Welcome to Inheritance - one of the coolest features in C#! Don't worry, I won't use big fancy words. We'll learn together, step by step.

Quick Question: Did you inherit your eye color from your parents? Or maybe your height? That's exactly what inheritance in C# is about - children getting traits from their parents!
๐ŸŽฏ After this lesson, you'll be able to:
  • โœ… Explain inheritance like a pro (but in simple words)
  • โœ… Create parent and child classes
  • โœ… Use the 'base' keyword (it's not scary, I promise!)
  • โœ… Override methods (change how things work)
  • โœ… Build your own inheritance hierarchies

Part 1: What is Inheritance? (The Easy Way)

In Simple Words: Inheritance is when one class inherits (gets) all the properties and methods from another class.
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ The Family Analogy

Imagine a Parent class called Animal:

  • ๐Ÿพ Every animal has a Name
  • ๐Ÿพ Every animal has an Age
  • ๐Ÿพ Every animal can Eat()
  • ๐Ÿพ Every animal can Sleep()

Now, a Child class called Dog inherits from Animal:

  • ๐Ÿ• Dog gets Name, Age, Eat(), Sleep()
  • ๐Ÿ• Dog adds its own things: Breed, Bark()
Result: Dog has everything Animal has + its own stuff!
๐Ÿ’ป Code Time!

Parent Class (Animal):

public class Animal
{
    public string Name;
    public int Age;
    
    public void Eat()
    {
        Console.WriteLine($"{Name} is eating!");
    }
}

Child Class (Dog):

public class Dog : Animal  // ๐Ÿ‘ˆ This means "inherits"
{
    public string Breed;
    
    public void Bark()
    {
        Console.WriteLine($"{Name} says Woof!");
    }
}
๐ŸŽ‰ Congratulations! You just created your first inheritance!
Dog automatically has Name, Age, and Eat()!
๐Ÿ˜‚ Fun Joke: Why did the inheritance class go to therapy? Because it had too many parent issues! (Get it? Parents? Inheritance? ...Okay, I'll stop ๐Ÿ˜…)

Part 2: The ':' Symbol - The Magic Link

๐Ÿ”— The Connection

The ':' symbol is like a bridge between parent and child.

public class Child : Parent  // ๐Ÿ‘ˆ The ':' means "inherits from"
{
    // Child gets everything from Parent
}
Read it as: "Child inherits from Parent"
or "Child is a Parent"
๐Ÿ“ Real Examples
// Dog IS AN Animal
public class Dog : Animal { }

// Car IS A Vehicle
public class Car : Vehicle { }

// Student IS A Person
public class Student : Person { }
Pro Tip: If you can say "X IS A Y", inheritance makes sense!
โœ… "A Dog IS AN Animal"
โŒ "A Dog IS A Car" (That would be weird!)

Part 3: The 'base' Keyword - Calling Mom and Dad

What is 'base'? It's like calling your parents when you need help! The 'base' keyword lets you call the parent's constructor or methods.
Calling Parent Constructor

When you create a child, the parent must be built first:

public class Animal
{
    public string Name;
    
    public Animal(string name)
    {
        Name = name;
        Console.WriteLine("๐Ÿพ Animal created!");
    }
}

public class Dog : Animal
{
    public string Breed;
    
    public Dog(string name, string breed) 
        : base(name)  // ๐Ÿ‘ˆ Calls parent first!
    {
        Breed = breed;
        Console.WriteLine("๐Ÿ• Dog created!");
    }
}

Output: "๐Ÿพ Animal created!" then "๐Ÿ• Dog created!"

Calling Parent Methods

You can also call parent methods:

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal makes a sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        base.MakeSound();  // ๐Ÿ‘ˆ First, do parent's thing
        Console.WriteLine("Dog barks: Woof!");  // Then add extra
    }
}

๐Ÿ”‘ base.MakeSound() runs the parent's version first!

๐Ÿ˜‚ Joke Time: Why did the child class call 'base'? Because it needed its parent's permission! (I know, I know... I'll stick to coding ๐Ÿ˜…)

Part 4: Virtual and Override - Changing the Rules

Sometimes, children want to change how they do things. That's where virtual and override come in!

virtual

Parent says: "You can change this if you want"

public virtual void Speak()
{
    Console.WriteLine("I speak...");
}
Parent gives permission
override

Child says: "I'm changing this!"

public override void Speak()
{
    Console.WriteLine("I bark!");
}
Child changes the behavior
Why Do This?
  • โœ… Make animals sound different
  • โœ… Make each car start differently
  • โœ… Customize behavior without changing parent
Dog d = new Dog();
d.Speak();  // "I bark!"
๐Ÿ”„ Real Example
public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Sound!");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}

public class Cow : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Moo!");
    }
}

๐ŸŽ‰ Each animal makes its own sound!

Part 5: Protected - The Family Secret

๐Ÿ›ก๏ธ What is Protected?

Protected means "Only me and my children can see this."

public class Person
{
    protected string SSN;  // Family secret
    public string Name;     // Everyone knows
}
โœ… Child Can See It
public class Employee : Person
{
    public void ShowSSN()
    {
        Console.WriteLine(SSN);  // โœ… Allowed! (Child can see)
    }
}

๐Ÿ”‘ Children can access protected members

public

๐ŸŒ Everyone

Like your name
protected

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Family Only

Like a family recipe
private

๐Ÿ”’ Just You

Like your password

Part 6: Building a Family Tree (Hierarchy)

You can create a chain of inheritance - like a family tree!

๐ŸŒณ The Animal Kingdom

Animal (Base)

Mammal + Fur, Tail

Bird + Wings, Fly

Fish + Fins, Swim

Dog + Breed

Cat + Meow

Eagle + Hunt

Salmon + Swim

Each level adds more specific features!

๐Ÿ’ป Code for This
public class Animal { public string Name; }
public class Mammal : Animal { public string Fur; }
public class Dog : Mammal { public string Breed; }
โœ… What Dog Inherits
  • โœ… From Animal: Name
  • โœ… From Mammal: Fur
  • โœ… Its own: Breed
Dog d = new Dog();
d.Name = "Rex";   // From Animal
d.Fur = "Brown";  // From Mammal
d.Breed = "Lab";  // Dog's own

Part 7: Sealed - The "No More Children" Rule

Sealed is like saying "I'm the last one - no more children after me!"

๐Ÿ”’ Sealed Class
public sealed class FinalClass
{
    public string Data;
}

// โŒ This will NOT work:
// public class Child : FinalClass { }  // ERROR!

โŒ Cannot inherit from a sealed class

โœ… When to Use Sealed
  • โœ… Security - Don't want anyone changing your code
  • โœ… Performance - Slightly faster
  • โœ… Design - Class is perfect as-is
Example: The string class is sealed - you can't inherit from it!

Part 8: Real-World Example - A Pizza Shop! ๐Ÿ•

Let's build a Pizza inheritance system - because who doesn't love pizza?

// Base Pizza - The Original ๐Ÿ•
public class Pizza
{
    public string Name = "Plain Pizza";
    public decimal Price = 10.00m;
    
    public virtual void Describe()
    {
        Console.WriteLine($"๐Ÿ• {Name} - ${Price}");
    }
}

// Pepperoni Pizza - A Child ๐Ÿ•+๐Ÿฅ“
public class PepperoniPizza : Pizza
{
    public PepperoniPizza()
    {
        Name = "Pepperoni Pizza";
        Price = 12.00m;
    }
    
    public override void Describe()
    {
        Console.WriteLine($"๐Ÿ• {Name} - ${Price} with lots of pepperoni!");
    }
}

// Supreme Pizza - A Child of Pizza ๐Ÿ•+๐Ÿฅ“+๐ŸŒถ๏ธ+๐Ÿง…
public class SupremePizza : Pizza
{
    public SupremePizza()
    {
        Name = "Supreme Pizza";
        Price = 14.00m;
    }
    
    public override void Describe()
    {
        Console.WriteLine($"๐Ÿ• {Name} - ${Price} with EVERYTHING!");
    }
}
// Gourmet Pizza - Sealed (No more changes!)
public sealed class GourmetPizza : Pizza
{
    public GourmetPizza()
    {
        Name = "Gourmet Pizza";
        Price = 20.00m;
    }
    
    public override void Describe()
    {
        Console.WriteLine($"๐Ÿ• {Name} - ${Price} with truffle oil!");
    }
}

// Program.cs - Ordering Pizzas
class Program
{
    static void Main()
    {
        Console.WriteLine("๐Ÿ• Welcome to C# Pizza Shop!\n");
        
        Pizza plain = new Pizza();
        PepperoniPizza pepperoni = new PepperoniPizza();
        SupremePizza supreme = new SupremePizza();
        GourmetPizza gourmet = new GourmetPizza();
        
        plain.Describe();      // Plain Pizza - $10.00
        pepperoni.Describe();  // Pepperoni Pizza - $12.00 with pepperoni!
        supreme.Describe();    // Supreme Pizza - $14.00 with EVERYTHING!
        gourmet.Describe();    // Gourmet Pizza - $20.00 with truffle oil!
    }
}
๐Ÿ• What this teaches:
  • โœ… Inheritance - All pizzas inherit from Pizza
  • โœ… Virtual/Override - Each pizza describes itself differently
  • โœ… Sealed - GourmetPizza can't be extended
  • โœ… Polymorphism - We treat all pizzas as Pizza!
๐Ÿ˜‚ Pizza Joke: Why did the pizza go to the doctor? Because it had too many toppings! (Okay, I'll stop now... maybe ๐Ÿ˜…)

Part 9: Let's Practice! ๐ŸŽฎ

What You're Building: A RPG Character System for a video game!
You'll create different character types (Warrior, Mage, Archer) that all share common traits but have their own special abilities.
๐ŸŽฎ About This Application

This is a Role-Playing Game (RPG) Character System. In video games like:

  • ๐ŸŽฏ World of Warcraft - Warriors, Mages, Hunters
  • โš”๏ธ Diablo - Barbarian, Wizard, Demon Hunter
  • ๐Ÿน Elder Scrolls - Warrior, Mage, Archer

Each character type shares common things (name, health, attack) but does things differently. This is perfect for inheritance because:

  • โœ… All characters are Characters (is-a relationship)
  • โœ… Each type adds its own special features
  • โœ… Each type changes (overrides) how they attack
Why this matters: This is how real game developers organize their code! Instead of writing separate code for each character type, they use inheritance to reuse code and keep things organized.
Your Mission:
  1. Base Class: Character
    • Properties: Name, Health
    • Method: Attack() - virtual
  2. Derived: Warrior
    • Property: Weapon
    • Override: Attack() - "swings sword"
  3. Derived: Mage
    • Property: Spell
    • Override: Attack() - "casts spell"
  4. Derived: Archer
    • Property: Bow
    • Override: Attack() - "shoots arrow"
๐Ÿ’ก How This Organizes Your Code
  • โœ… Common code (Name, Health) goes in Character - write once!
  • โœ… Special code (Weapon, Spell, Bow) goes in each child class
  • โœ… Different behavior (Attack) uses override - each type attacks differently
  • โœ… Easy to add new character types later (just create another child)
Result: Clean, organized code that's easy to understand and expand!
๐ŸŽฏ Goal: By the end of this exercise, you'll have a working RPG character system that demonstrates inheritance, base keyword, virtual/override, and polymorphism - just like professional game developers use!

๐ŸŽ‰ What You Learned Today!

Inheritance
Child gets parent's traits
'base' Keyword
Call your parent
virtual/override
Change how things work
protected
Family-only access
Hierarchy
Multi-level inheritance
sealed
No more children
Real Example
Pizza Shop! ๐Ÿ•
Test Your Knowledge - Take Quiz