Hard csharp

OOP — Polymorphism with Shape hierarchy

Problem

Abstract Shape with Circle and Rectangle overriding Area().

Hints
  • abstract Area(), override in subclasses

Your practice code

Ready — edit the code above and click Run.

Solution

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.

Explanation

Runtime polymorphism via abstract base + override—expect this in .NET OOP interviews.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details