CodeBlanks Logo Icon CodeBlanks

sealed and abstract

C# course · Intermediate · Lesson 57/116

Learn the sealed abstract combination and its constraints.

sealed and abstract

sealed prevents a class from being inherited. abstract requires inheritance. So a class cannot be both sealed and abstract at the same time; this is an invalid combination.

However, a sealed override method is valid: a subclass of an abstract class can mark an overridden abstract method as sealed to prevent further subclasses from overriding it. public sealed override void MakeSound() is the final implementation.

When to use sealed?

Use sealed when you don't want a class's behavior to be changed. It can be for security-critical classes, performance optimization or a design decision.

Example: string is a sealed class because changing its core behavior would be dangerous. A Dog subclass can mark MakeSound as sealed to prevent subclasses from changing the "woof woof" behavior.

Exercise Sealed dog

Define the Dog class: it inherits Animal and overrides MakeSound as public sealed override void MakeSound(). The body does Console.WriteLine("Woof");. In Main, create Animal a = new Dog(); and call a.MakeSound();.

Show example solution
Animal { public sealed override void MakeSound() { Console.WriteLine("Woof"); } }`. In Main write `Animal a = new Dog(); a.MakeSound();`.
Example solution:
using System;

abstract class Animal
{
    public abstract void MakeSound();
}

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

class Program
{
    static void Main()
    {
        Animal a = new Dog();
        a.MakeSound();
    }
}

Test yourself

  1. Match: sealed and abstract

    sealed class
    cannot be inherited
    sealed override
    cannot be overridden further
    abstract class
    must be inherited
    sealed + abstract class
    invalid combination
  2. Which statement about sealed and abstract is correct?

    • A class can be both sealed and abstract.
    • A sealed method can be overridden.
    • A sealed override is used for methods that cannot be overridden in further subclasses.
    • A sealed abstract method can be defined.
    Show answer

    A sealed override is used for methods that cannot be overridden in further subclasses. — Correct. A sealed override marks the final implementation that further subclasses cannot override.

  3. Fill in the blank: sealed override

    public ____ override void MakeSound()
    {
        Console.WriteLine("Woof");
    }
    Show answer
    public sealed override void MakeSound()
    {
        Console.WriteLine("Woof");
    }

All lessons in Intermediate