Polymorphism
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: