Monday, 17 November 2025

C# Inheritance Concepts

C# Inheritance Concepts

C# Inheritance & Keywords

1. The sealed Keyword (C# version of Java's final)

C# does not use the keyword final. Instead, it uses sealed to:

  • Stop a class from being inherited
  • Stop a method from being overridden again

Sealed Class Example

sealed class Car { }

Sealed Method Example

class A { public virtual void Show() { } } class B : A { public sealed override void Show() { } }

2. Multilevel Inheritance Example Using Car Classes

Multilevel inheritance means:

Car → SportsCar → RaceCar

C# Example

class Car // Level 1 (Base Class) { public void Start() { Console.WriteLine("Car starts."); } } class SportsCar : Car // Level 2 (Inherits from Car) { public void Turbo() { Console.WriteLine("SportsCar activates turbo."); } } class RaceCar : SportsCar // Level 3 (Inherits from SportsCar) { public void Nitro() { Console.WriteLine("RaceCar boosts with nitro!"); } } class Program { static void Main() { RaceCar rc = new RaceCar(); rc.Start(); // from Car rc.Turbo(); // from SportsCar rc.Nitro(); // from RaceCar } }

Output:

Car starts. SportsCar activates turbo. RaceCar boosts with nitro!

No comments:

Post a Comment