C# Abstract Classes
An abstract class is a class that cannot be instantiated directly and is meant to be a base for other classes. It can contain abstract methods (with no body) that derived classes must implement, as well as regular methods with shared implementation.
Abstract classes are useful when you want to define a common structure and some shared behavior for related classes, while forcing each derived class to implement certain specifics.
abstract class Base {
public abstract void Method();
}
class Derived : Base {
public override void Method() { }
}Defining an abstract class
An abstract class is marked with the `abstract` keyword. It can have both abstract methods (no implementation) and concrete methods (with implementation) that derived classes inherit.
Implementing abstract methods
Any non-abstract class deriving from an abstract class must implement all its abstract methods using the `override` keyword, or it must also be declared abstract.
using System;
abstract class Shape {
public abstract double Area();
}
class Square : Shape {
public double Side;
public Square(double side) { Side = side; }
public override double Area() { return Side * Side; }
}
class Program {
static void Main() {
Shape s = new Square(4);
Console.WriteLine(s.Area());
}
}16Square must implement Area() because Shape declares it as abstract.
using System;
abstract class Animal {
public abstract void MakeSound();
public void Sleep() {
Console.WriteLine("Zzz...");
}
}
class Cat : Animal {
public override void MakeSound() {
Console.WriteLine("Meow");
}
}
class Program {
static void Main() {
Cat c = new Cat();
c.MakeSound();
c.Sleep();
}
}Meow
Zzz...Cat implements the abstract MakeSound() method and also inherits the concrete Sleep() method.
Key points
- Abstract classes cannot be instantiated directly.
- Abstract methods have no body and must be implemented by derived classes.
- Abstract classes can still contain regular, fully implemented methods.
- Attempting `new` on an abstract class causes a compile error.
