Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// Inheritance, abstract classes, virtual dispatch public abstract class Shape { public string Color { get; set; } = "Black"; public abstract double Area(); // must be overridden public virtual string Describe() => // can be overridden $"{GetType().Name} (color={Color}, area={Area():F2})"; } public class Circle : Shape { public double Radius { get; } public Circle(double radius) => Radius = radius; public override double Area() => Math.PI * Radius * Radius; } public class Rectangle : Shape { public double Width { get; } public double Height { get; } public Rectangle(double w, double h) { Width = w; Height = h; } public override double Area() => Width * Height; public override string Describe() => base.Describe() + $" [{Width}x{Height}]"; } // Sealed — no further subclassing allowed public sealed class Square : Rectangle { public Square(double side) : base(side, side) { } } // Polymorphic usage List<Shape> shapes = new() { new Circle(5) { Color = "Red" }, new Rectangle(4, 6) { Color = "Blue" }, new Square(3) { Color = "Green" } }; foreach (var shape in shapes) Console.WriteLine(shape.Describe()); double totalArea = shapes.Sum(s => s.Area()); Console.WriteLine($"Total area: {totalArea:F2}");
Result
Open