sealed
Learn to prevent inheritance with sealed.
sealed class
If you mark a class sealed, no other class can inherit from it. The declaration is: sealed class Logger { ... }. This states the class is a final type.
Sealing is useful for two reasons: first, to close the design and prevent unwanted changes through inheritance; second, to let the compiler and runtime speed up calls to overridden methods, because no subclass of a sealed class will ever exist.
sealed method
sealed is not only for classes; it can also be applied to override methods: you can seal public override void Log() { ... } so that further subclasses cannot override it again.
This is useful when a derived class wants to fix a behavior. The method can be sealed without sealing the whole class; only that method's inheritance chain is cut off.
Exercise Define the Logger class as sealed
Declare a Logger class as sealed. Add a public void Log(string message) method with Console.WriteLine(message); in the body. Inside Main create an instance with new Logger() and call Log("Logging started").
Show example solution
Declare Logger as sealed class. Add the Log method. In Main write Logger l = new Logger(); l.Log("Logging started");
Example solution:
using System;
sealed class Logger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
class Program
{
static void Main()
{
Logger l = new Logger();
l.Log("Logging started");
}
}
Test yourself
-
What happens with sealed class Logger?
sealed class Logger { }- Logger can be inherited
- Logger methods are removed
- Logger becomes static
- Logger cannot be inherited
Show answer
Logger cannot be inherited — Correct. A sealed class cannot be inherited from.
-
Complete the sealed declaration
class Logger { }____Show answer
class Logger { }sealed -
Match each sealed usage to its purpose
- sealed class
- Class is sealed
- sealed override
- Method is sealed
- sealed
- Closes inheritance
- Logger
- The sealed class