Junior
What is an abstract class?
sobes.tech AI
Answer from AI
An abstract class is a class that cannot be instantiated directly. It serves as a base class for other classes and can contain abstract members (methods, properties, indexers, events) that must be implemented in derived classes.
Main features:
- Declared with the keyword
abstract. - Can contain both abstract and non-abstract (regular) members.
- Abstract members do not have an implementation in the base class.
- A derived class must either implement all abstract members of the base class or be declared as abstract itself.
It is used to define a common contract for a group of related classes and to implement the Template Method pattern.
// Declaration of an abstract class
public abstract class Shape
{
// Abstract method - has no implementation
public abstract double Area();
// Non-abstract method
public void Display()
{
Console.WriteLine("This is a shape.");
}
}
// Derived class inheriting from the abstract class
public class Circle : Shape
{
public double Radius { get; set; }
// Implementation of the abstract method Area
public override double Area()
{
return Math.PI * Radius * Radius;
}
}