CodeBlanks Logo Icon CodeBlanks

abstract class

Learn to define and derive an abstract class.

Abstract class

An abstract class cannot be instantiated directly and is designed to be inherited. Declaration: abstract class Animal { ... }.

An abstract class can hold both bodied methods and abstract methods (bodyless signatures). Calling new Animal() is a compile error; but you can use it through an instance of a derived class: Animal a = new Dog();. This is useful to share common behavior.

Cannot instantiate but can be inherited

An abstract class cannot be created with new: new Animal() is a compile error. Instead you define a subclass and instantiate it: class Dog : Animal { ... }.

The subclass must implement all the abstract class's abstract methods. Otherwise you get a compile error. This way the abstract class acts as a template for subclasses. Common fields and helper methods live in the abstract class; details are left to subclasses.

Practice Animal class

Define the Animal abstract class with a public string Name; field and a public abstract void MakeSound(); method. Dog and Main are already in place; you only add the abstract class.

Starter code

Program.cs
using System;

// Define the Animal abstract class: Name field and MakeSound abstract method

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof woof");
    }
}

class Program
{
    static void Main()
    {
        // Create a dog, set its name and print its sound
    }
}

Sample solution

Program.cs
using System;

abstract class Animal
{
    public string Name;

    public abstract void MakeSound();
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof woof");
    }
}

class Program
{
    static void Main()
    {
        Animal a = new Dog();
        a.Name = "Rex";
        Console.WriteLine(a.Name);
        a.MakeSound();
    }
}

Expected output

Karabaş
Hav hav

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: abstract class

Question
abstract ____
{
    public string Name;
    public abstract void MakeSound();
}
Answer
abstract class Animal
{
    public string Name;
    public abstract void MakeSound();
}

Explanation: `class Animal` declares the abstract class.

2 Which statement about abstract classes is correct?

  • An abstract class can be instantiated with new.
  • An abstract class is designed to be inherited. Correct answer
  • An abstract class can only contain methods.
  • An abstract class can be sealed.

Explanation: An abstract class is designed to be inherited; it cannot be instantiated directly.

3 Match: abstract class concepts

Term Meaning
abstract class designed for inheritance
new Animal() compile error
abstract method bodyless signature
override body in derived class

All lessons in Intermediate