Start learning free

LESSON 188 OF 347 · OBJECT-ORIENTED PROGRAMMING

Abstract Classes in C#: Abstract Methods and Contracts

Lesson Read the full explanation

TL ; DR:

An abstract class is a class you can't instantiate directly — it's a half-finished template. It can declare methods with no body (abstract methods) that any concrete subclass must implement.


abstract class Animal {
    public abstract void Speak();   // no body — concrete
                                      // subclasses must provide one
}
class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Woof");
    }
}


Full lesson:

Sometimes you want to capture shared behavior across a family of classes without committing to one concrete implementation. For example, every Animal can speak(), but exactly how depends on whether it's a Dog or a Cat. That's what abstract classes are for.

Two superpowers

  1. You can't write new Animal() directly — the compiler/runtime stops you. You have to pick a concrete subclass.
  2. Any subclass MUST implement every abstract method, or the compiler/runtime complains. The abstract class is a contract with teeth.

Mixing abstract and concrete

An abstract class can also have concrete methods (with bodies) and fields. Those are shared by all subclasses for free, just like normal inheritance. Only the methods marked abstract require an override.

Notes by language

  • C# / Java — keyword abstract on the class and on the method.
  • Python — inherit from abc.ABC and decorate the method with @abstractmethod.
  • JavaScript — no built-in support. The convention is a parent class whose method throws an error if not overridden.
  • C++ — a method ending with = 0 is "pure virtual"; a class with any pure virtual method is abstract.

Your task

The abstract Animal class is already defined. Create a concrete Dog subclass and implement the speak method so it prints "Woof". The harness builds a Dog and calls speak().

Expected output:

Woof
STEP 1 OF 2
    Ctrl + Enter to check

    C# · OBJECT-ORIENTED PROGRAMMING

    Abstract Classes in C#, explained

    What an abstract class is

    Sometimes a base class describes a family of types without being a complete thing itself. Every Animal can speak, but "an animal" in general makes no particular sound. An abstract class is a class you can't create objects from. It is a half-finished template that concrete subclasses complete.

    Two rules

    1. You can't instantiate it. new Animal() is a compile error (CS0144: cannot create an instance of the abstract type). You have to create a concrete subclass instead.
    2. Subclasses must finish it. An abstract class may declare abstract methods: methods with a signature but no body. Every non-abstract subclass has to implement all of them, or the compiler rejects the class. The abstract class is a contract that the compiler enforces.

    The syntax

    abstract class Animal {
        public abstract void Speak();   // no body, ends with a semicolon
    }
    
    class Dog : Animal {
        public override void Speak() {
            Console.WriteLine("Woof");
        }
    }
    

    The keyword abstract appears on the class and on each abstract method. The subclass implements the method with override, exactly as with a virtual method. Two further rules apply to the override:

    • The override must keep the same accessibility. An abstract method that is public can't be overridden as protected or private.
    • The same name and parameters are required, or the method doesn't count as the implementation.

    An abstract method can only appear inside an abstract class. Declaring one in a normal class is a compile error.

    Mixing abstract and concrete members

    An abstract class can also contain ordinary members: fields, constructors and methods with bodies. The subclasses inherit them as usual. Only the abstract methods have to be overridden.

    abstract class Animal {
        public string name;
    
        public Animal(string name) {
            this.name = name;
        }
    
        public abstract void Speak();
    
        public void Introduce() {
            Console.Write(name + ": ");
            Speak();
        }
    }
    
    class Dog : Animal {
        public Dog() : base("Rex") { }
        public override void Speak() {
            Console.WriteLine("Woof");
        }
    }
    

    Here Introduce is written once, in the abstract class, and calls Speak, which each subclass supplies. new Dog().Introduce() prints Rex: Woof. The abstract class has a constructor even though you can't call it with new: the subclass calls it with : base(...).

    Abstract classes and polymorphism

    You can't create an Animal, but you can still use the type for variables, parameters and arrays:

    Animal a = new Dog();
    a.Speak();   // Woof
    

    The variable has the abstract type, and the object is a concrete subclass. The call runs the subclass's override, just as in the previous lesson.

    Common mistakes

    • Trying to instantiate the abstract class. new Animal() never compiles.
    • Not implementing every abstract method. A class that derives from Animal without overriding Speak gets an error that it doesn't implement the inherited abstract member. Mark that class abstract too if you want to leave the work to its own subclasses.
    • Leaving out override. A method named Speak without the keyword doesn't implement the abstract one. You get the same missing-member error, plus a warning that it hides the inherited method.
    • Changing the access level. An abstract public method must be overridden as public.
    • Giving an abstract method a body. Abstract methods end in a semicolon, with no braces. Use virtual if you want a default implementation that subclasses may replace.
    • Using lowercase names. The lesson's method is Speak, in PascalCase.

    The exercise, step by step

    The abstract Animal class is given. MainFunction creates a Dog named rex and calls Speak on it, but the Dog class doesn't exist yet. The expected output is:

    Woof
    
    1. Declare the subclass below Animal: class Dog : Animal. Since Animal can't be instantiated, you need a concrete class for MainFunction to create.
    2. Implement the abstract method inside Dog: public override void Speak(), with a body that writes Woof using Console.WriteLine. The override keyword is required, and public matches the base declaration.
    abstract class Animal {
        public abstract void Speak();
    }
    
    class Dog : Animal {
        public override void Speak() {
            Console.WriteLine("Woof");
        }
    }
    
    class Solution {
        public void MainFunction() {
            Dog rex = new Dog();
            rex.Speak();
        }
    }
    

    Key takeaways

    • An abstract class can't be instantiated; it is meant to be inherited.
    • Abstract methods have no body and must be overridden by every concrete subclass.
    • Abstract classes can also hold fields, constructors and normal methods.
    • Use override with the same accessibility to implement an abstract method.
    • Variables of the abstract type can refer to concrete subclass objects, which gives you polymorphism.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free