Inheritance in C#
Build a SportsCar from the Car design without rewriting everything.
60-Second Version: Inheritance = reuse code.
SportsCar : Car means SportsCar gets everything from Car, then adds its own stuff.1. The Base Design = Parent Class
This is the general Car we built last time. All cars have this.
public class Car
{
public string Owner;
protected int Speed; // protected: Children can access
public void Start() { Console.WriteLine($"{Owner}'s car started"); }
}
2. The Specialized Design = Child Class
: means "inherits from". SportsCar gets Owner, Speed, and Start() for free.
public class SportsCar : Car // SportsCar IS-A Car
{
public bool HasTurbo; // Only SportsCar has this
public void ActivateTurbo()
{
Speed += 50; // OK: Can access protected Speed from parent
Console.WriteLine($"Turbo! Speed: {Speed}");
}
}
3. Using It
SportsCar kunalCar = new SportsCar();
kunalCar.Owner = "Kunal"; // Inherited from Car
kunalCar.HasTurbo = true; // Specific to SportsCar
kunalCar.Start(); // Inherited from Car
kunalCar.ActivateTurbo(); // Specific to SportsCar
Beginner Trap:
kunalCar.Speed = 100; fails. Speed is protected. Only code inside Car or SportsCar can touch it. Outside code cannot.
Quick Check ๐ง
Next: Polymorphism - Using a
Car variable to drive a SportsCar, Sedan, or Truck without knowing which one it is.
No comments yet. Be the first to share your thoughts!