Abstract Shape with Circle and Rectangle overriding Area().
Ready — edit the code above and click Run.
using System;
abstract class Shape { public abstract double Area(); }
class Circle : Shape {
double _r;
public Circle(double r) => _r = r;
public override double Area() => Math.PI * _r * _r;
}
class Rectangle : Shape {
double _w, _h;
public Rectangle(double w, double h) { _w = w; _h = h; }
public override double Area() => _w * _h;
}
class Program {
static void Main() {
Shape[] shapes = { new Circle(2), new Rectangle(3, 4) };
foreach (var s in shapes) Console.WriteLine(s.Area());
}
}
Try solving on your own first, then reveal the official answer.
Runtime polymorphism via abstract base + override—expect this in .NET OOP interviews.