You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Inheritance and interfaces are core pillars of object-oriented programming in C#. They enable code reuse, polymorphism, and the design of flexible, extensible systems.
A class can inherit from a single base class:
public class Animal
{
public string Name { get; set; }
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine($"{Name} says: Woof!");
}
}
var dog = new Dog { Name = "Rex" };
dog.Eat(); // Inherited from Animal
dog.Bark(); // Defined in Dog
Important: C# supports single inheritance only — a class can inherit from one base class, but can implement multiple interfaces.
Use virtual and override for runtime polymorphism:
public class Shape
{
public virtual double Area() => 0;
public virtual string Describe() => "I am a shape.";
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area() => Math.PI * Radius * Radius;
public override string Describe() => $"Circle with radius {Radius}";
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area() => Width * Height;
public override string Describe() => $"Rectangle {Width}x{Height}";
}
// Polymorphism in action
Shape[] shapes = { new Circle { Radius = 5 }, new Rectangle { Width = 3, Height = 4 } };
foreach (var shape in shapes)
{
Console.WriteLine($"{shape.Describe()} — Area: {shape.Area():F2}");
}
Abstract classes cannot be instantiated and may contain abstract (unimplemented) members:
public abstract class Vehicle
{
public string Make { get; set; }
public int Year { get; set; }
// Abstract method — must be implemented by derived classes
public abstract double FuelEfficiency();
// Concrete method — shared by all derived classes
public string Summary() => $"{Year} {Make} — {FuelEfficiency():F1} mpg";
}
public class Car : Vehicle
{
public override double FuelEfficiency() => 35.0;
}
public class Truck : Vehicle
{
public override double FuelEfficiency() => 18.5;
}
Prevent a class from being inherited:
public sealed class Singleton
{
private static readonly Singleton _instance = new();
private Singleton() { }
public static Singleton Instance => _instance;
}
// public class MySingleton : Singleton { } // Error! Cannot inherit from sealed class
Interfaces define a contract — a set of members that implementing classes must provide:
public interface IShape
{
double Area();
double Perimeter();
}
public interface IDrawable
{
void Draw();
}
public class Square : IShape, IDrawable
{
public double Side { get; set; }
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.