C# Abstract Classes
An abstract class is a class that cannot be used to create objects. It holds methods that derived classes must complete.
An abstract method completed
Animal declares Sound with no body. Dog completes the method with override.
using System;
abstract class Animal
{
public abstract void Sound();
}
class Dog : Animal
{
public override void Sound()
{
Console.WriteLine("Woof");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
dog.Sound();
}
}A regular method too
Animal also holds a regular Sleep method here. Dog uses it without writing a copy.
using System;
abstract class Animal
{
public abstract void Sound();
public void Sleep()
{
Console.WriteLine("Zzz");
}
}
class Dog : Animal
{
public override void Sound()
{
Console.WriteLine("Woof");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
dog.Sound();
dog.Sleep();
}
}Creating an abstract object fails
This code tries to create an Animal object directly. The compiler refuses the program.
using System;
abstract class Animal
{
public abstract void Sound();
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal();
}
}Example
using System;
abstract class Payment
{
public abstract void Pay();
}
class CardPayment : Payment
{
public override void Pay()
{
Console.WriteLine("Paid by card");
}
}
class CashPayment : Payment
{
public override void Pay()
{
Console.WriteLine("Paid by cash");
}
}
class Program
{
static void Main(string[] args)
{
Payment first = new CardPayment();
Payment second = new CashPayment();
first.Pay();
second.Pay();
}
}Key points
- The abstract keyword marks a class as abstract.
- An abstract method has a name and no body.
- A derived class completes an abstract method with override.
- An abstract class can also hold regular methods with bodies.
- Objects come from the derived classes, not the abstract class.
In this example, Payment is abstract and declares Pay with no body. CardPayment completes Pay and prints the card line. CashPayment completes Pay and prints the cash line. Both objects come from derived classes.
Note
The compiler refuses new on an abstract class.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What happens when code runs new Animal() and Animal is abstract?