Sobes.tech
Junior

Have you used abstract classes?

sobes.tech AI

Answer from AI

Yes, I have used them. Abstract classes are necessary for defining common base behavior and structure for derived classes when the base class itself is not intended to be instantiated.

They are useful when:

  • You need to define a common interface and partial implementation for a group of related classes.
  • You want to prevent instantiation of the base class.
  • There should be abstract members (methods, properties, indexers, events) that must be implemented in derived classes.

Example of usage:

// Abstract base class
public abstract class Shape
{
    // Abstract method, must be implemented in derived classes
    public abstract double GetArea();

    // Non-abstract method with implementation
    public void DisplayShapeType()
    {
        Console.WriteLine("This is a shape.");
    }
}

// Derived class implementing BoundedShape
public class Circle : Shape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    // Implementation of abstract method
    public override double GetArea()
    {
        return Math.PI * Radius * Radius;
    }
}

// Another derived class
public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }

    // Implementation of abstract method
    public override double GetArea()
    {
        return Width * Height;
    }
}