Chapter 12: Inheritance

1. What is Inheritance? (Super Simple Analogy)

Think of inheritance like a family tree:

  • Base class (Parent) → has common traits that all children share Example: Vehicle has Speed, Color, StartEngine()
  • Derived class (Child)inherits everything from the parent and can add its own special features Example: Car inherits from Vehicle and adds NumberOfDoors, Drift()
  • Grandchild → can inherit from Car Example: SportsCar inherits from Car and adds TurboBoost()

Key benefit: You don’t repeat code — common behavior lives in the base class.

2. Defining Base and Derived Classes

Syntax:

C#

Real example – Vehicle hierarchy

C#
C#
C#

Output:

text

3. virtual & override – The Magic of Polymorphism

  • virtual → Marks a method/property in base class as overridable
  • override → In derived class, provides a new implementation

This is the key to polymorphism — treating different objects the same way but getting different behavior.

Example – Animals talking differently

C#

Output:

text

4. new Keyword – Hiding (Not Overriding) Base Members

If you don’t use virtual/override, you can hide the base method using new.

C#

Rule of thumb: Use override when you want polymorphic behavior (most common). Use new only when you really want to hide the base method (rare, can be confusing).

5. Sealed Classes & Sealed Methods

  • sealed classCannot be inherited from (final class)
C#
  • sealed override → Child class prevents further overriding
C#

When to use sealed?

  • When you don’t want anyone to extend your class/method (security, performance, design decision)
  • Common in utility classes, final implementations

Mini-Project: Employee Hierarchy with Inheritance

C#

Summary – What We Learned Today

  • Inheritance → class Child : Parent
  • virtual & override → polymorphic behavior
  • new → hides base member (rarely used)
  • sealed → prevents further inheritance/overriding
  • base keyword → call parent constructor/method
  • Polymorphism → treat derived objects as base type

Your Homework (Super Fun & Practical!)

  1. Create a new console project called InheritanceMaster
  2. Create a base class Shape with:
    • Properties: Color
    • virtual method: Draw() and CalculateArea()
  3. Create derived classes:
    • Circle (Radius)
    • Rectangle (Width, Height)
    • Triangle (Base, Height)
    • Override Draw() and CalculateArea() for each
  4. In Program.cs: Create an array of Shapes, draw each, and calculate total area

Next lesson: Polymorphism in Depth + Abstract Classes & Interfaces – we’re going to make our code even more flexible and powerful!

You’re doing absolutely fantastic! 🎉 Any part confusing? Want more examples with virtual, override, or sealed? Just tell me — I’m right here for you! 💙

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *