Inheritance, Polymorphism, virtual & override Masterclass
๐ Covered in this chapter:
Base & Derived Classes ยท base Keyword ยท virtual & override ยท Runtime Polymorphism ยท Abstract Classes ยท Upcasting & Downcasting ยท OOP Pillars
Welcome to Phase 6 (Chapter 17): C# Inheritance, Polymorphism, virtual & override Masterclass! Inheritance allows a derived class to inherit fields and methods from a base class. Polymorphism allows objects of different derived types to be treated through a single base class reference. C# OOP is founded on four major principles: Abstraction, Encapsulation, Inheritance, and Polymorphism.
1Inheritance & Virtual Method Overriding
C# โ Virtual Method Overriding
โถ Run in Compiler
class Animal
{
public string Name { get; set; }
public Animal(string name)
{
Name = name;
}
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal
{
public Dog(string name) : base(name) { }
public override void MakeSound()
{
Console.WriteLine($"{Name} barks: Woof! Woof!");
}
}
Animal animal = new Dog("Buddy");
animal.MakeSound(); // Output: Buddy barks: Woof! Woof!
2Abstract Classes & Methods
C# โ Abstract Class Example
โถ Run in Compiler
abstract class Shape
{
public abstract double CalculateArea(); // Abstract method (no body!)
}
class Circle : Shape
{
public double Radius { get; set; }
public Circle(double r) => Radius = r;
public override double CalculateArea() => Math.PI * Radius * Radius;
}
Shape s = new Circle(5.0);
Console.WriteLine($"Circle Area: {s.CalculateArea():F2}");
3Technical FAQs
Q1: What are the four major OOP principles in C#?
Abstraction, Encapsulation, Inheritance, and Polymorphism.
Q2: Can I instantiate an abstract class?
No! Abstract classes cannot be instantiated with new. They serve as base templates for derived classes.