Polymorphism
Polymorphism means many forms: different objects can answer the same command in their own ways. Tell every animal to speak, and the dog barks while the cat meows.
In this page:
Syntax
BaseType variable = new DerivedType();
variable.MethodName(); // runs the DerivedType override
List<BaseType> items = new List<BaseType> { new DerivedA(), new DerivedB() };
Polymorphism
Polymorphism lets you treat objects of different derived types uniformly through a shared base type or interface, while each still runs its own overridden behavior.
A single List<Shape> can hold circles, squares, and triangles, and calling Area() on each invokes the right implementation automatically. This is what makes overriding genuinely useful rather than just syntax.
Note:
Polymorphism is why you can write one loop that works correctly no matter which subclass each object actually is.
Example: Polymorphism
using System;
using System.Collections.Generic;
class Shape
{
public virtual double Area() => 0;
}
class Circle : Shape
{
public double Radius;
public Circle(double r) { Radius = r; }
public override double Area() => Math.PI * Radius * Radius;
}
class Square : Shape
{
public double Side;
public Square(double s) { Side = s; }
public override double Area() => Side * Side;
}
class Program
{
static void Main(string[] args)
{
List<Shape> shapes = new List<Shape> { new Circle(2), new Square(3) };
foreach (Shape s in shapes)
{
Console.WriteLine(s.Area());
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting
virtualandoverride, so the base version is called through a base reference. - Calling a derived-only method through a base reference, which does not compile.
- Confusing method hiding with
newwith true overriding.
Chapter Summary
- Inheritance lets a class reuse another class, with
baseaccessing the parent. - Method overriding and polymorphism let derived classes change behavior.
- Abstract and sealed classes control how classes can be extended.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: