← C# from Scratch
Lesson 33 of 39 · 10 XP
Polymorphism
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
The parent declares a method virtual, and the subclass overrides it with override.
Which version gets called is decided at run time, by the object's actual type:
class Shape
{
public virtual double Area() => 0;
public override string ToString() => $"{GetType().Name} {Area():F2}";
}
class Circle : Shape
{
double r;
public Circle(double r) { this.r = r; }
public override double Area() => Math.PI * r * r;
}
Shape[] shapes = { new Circle(1), new Square(2) };
foreach (Shape s in shapes)
Console.WriteLine(s.Area()); // each has its own Area
- without
virtual/override, the call is decided by the type of the variable, not the object (and the compiler warns you aboutnew); base.Area()calls the parent's version from an override;ToString()is a virtual method ofobjectitself: it's overridden so thatConsole.WriteLine(obj)prints something meaningful.
Under the hood. Every class has a virtual method table (vtable); an object holds a reference to the table of its real class, and the call goes through it.
Task. Finish Circle(r), Square(a) and Triangle(a, h) (area a·h/2), overriding Area().
The program reads shapes (circle 1, square 2, triangle 3 4) and prints each one and the total area.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.