Circle Cylinder Example of Inheritance in C# - Biz Tech

Circle Cylinder Example of Inheritance in C#

Listen
using System;

class Program
{
    static void Main(string[] args)
    {
        Circle c = new Circle(5);
        Console.WriteLine("Circle area: " + c.GetArea());

        Cylinder cy = new Cylinder(5, 10);
        Console.WriteLine("Cylinder area: " + cy.GetArea());
        Console.WriteLine("Cylinder volume: " + cy.GetVolume());
    }
}

class Circle
{
    protected double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public virtual double GetArea()
    {
        return Math.PI * radius * radius;
    }
}

class Cylinder : Circle
{
    private double height;

    public Cylinder(double radius, double height) : base(radius)
    {
        this.height = height;
    }

    public override double GetArea()
    {
        return 2 * base.GetArea() + 2 * Math.PI * radius * height;
    }

    public double GetVolume()
    {
        return base.GetArea() * height;
    }
}
 

In this example, we have a base class Circle and a derived class Cylinder. The Circle class has a protected field radius and a method GetArea() that calculates the area of the circle. The Cylinder class inherits from Circle and adds a private field height, as well as methods GetArea() and GetVolume() that calculate the area and volume of the cylinder, respectively.

In the Main() method, we create a Circle object and a Cylinder object, and call their respective GetArea() and GetVolume() methods. Because Cylinder inherits from Circle, we can treat the Cylinder object as a Circle object and call the GetArea() method on it, which is overridden in the Cylinder class to calculate the area of the cylinder.

When we run the program, it outputs the following:

Circle area: 78.53981633974483
Cylinder area: 471.23889803846896
Cylinder volume: 3926.9908169872414

This demonstrates inheritance, where a derived class inherits the fields and methods of a base class and can add its own fields and methods or override existing ones. This promotes code reuse and allows for more efficient and modular design.