Skip to Content
Course content

163: The abstract and sealed Modifiers

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years back, I was reviewing a pull request for a junior developer working on a payment gateway. He'd built a PaymentProcessor class with a ProcessPayment() method. The problem was, the PaymentProcessor itself didn't actually do anything—it was just there to ensure that CreditCardProcessor and PayPalProcessor shared the same interface. But because he forgot to mark the base class as abstract, another developer on the team accidentally instantiated new PaymentProcessor() in a factory method. The code compiled perfectly, but at runtime, it did absolutely nothing. We spent an entire afternoon hunting a bug that a single keyword could have prevented at compile-time.

Enforcing a Blueprint with Abstract

When you mark a class as abstract, you're telling the C# compiler, "This class is an idea, not a thing." You cannot create an instance of an abstract class using the new keyword. Its sole purpose is to be inherited from. This is incredibly useful when you have a general concept that doesn't make sense on its own, but provides a foundation for more specific versions.

Within an abstract class, you can also define abstract methods. These are methods that have no body—just a signature. By doing this, you're forcing any non-abstract class that inherits from it to provide its own implementation. It's essentially a contract. If you don't implement that method in the child class, the code won't even compile.

public abstract class PaymentMethod
{
    public string AccountHolder { get; set; }

    // Every payment method must have a way to authorize, 
    // but the "how" depends entirely on the specific method.
    public abstract bool Authorize(decimal amount);
}

public class CreditCard : PaymentMethod
{
    public override bool Authorize(decimal amount)
    {
        Console.WriteLine($"Authorizing credit card for {amount:C}...");
        return true; // Logic for CC authorization goes here
    }
}

I've found that using abstract classes is often cleaner than using interfaces when your derived classes share some actual logic (like the AccountHolder property above) but need to diverge on the critical behavior.

Locking Down Logic with Sealed

On the opposite end of the spectrum, we have the sealed modifier. If abstract is an open invitation to inherit, sealed is a "No Trespassing" sign. When you mark a class as sealed, no other class can inherit from it.

You might wonder why you'd ever want to prevent inheritance. In my experience, this usually comes down to two things: security and intent. Sometimes, a class is so specialized that allowing someone to override its behavior could introduce critical bugs or security vulnerabilities. Other times, it's a performance hint to the JIT compiler; since the compiler knows there are no derived classes, it can sometimes optimize method calls (devirtualization) because it doesn't have to look up the method in a virtual table.

public sealed class SecureVaultProcessor : PaymentMethod
{
    public override bool Authorize(decimal amount)
    {
        // This logic is highly sensitive and must not be altered by a subclass
        Console.WriteLine("Performing high-security vault authorization...");
        return true;
    }
}

// This would cause a compile-time error:
// public class HackyVault : SecureVaultProcessor { } 

You can also use sealed on specific methods that are overrides of a base class. This allows a class to be inheritable, but tells any further descendants, "You can inherit from me, but you cannot change how this specific method works." This is a great way to maintain control over a class hierarchy as it grows.




📋 Practical Task

Building a Restricted Banking Transaction Hierarchy

Your task is to implement a simplified banking system that uses both abstract and sealed modifiers to ensure the system is robust and cannot be misused.

  • Create an abstract class called BankTransaction. It should have a property for Amount and an abstract method called Execute() that returns a boolean.
  • Create a class called Deposit that inherits from BankTransaction and implements the Execute() method to print "Depositing funds..." and return true.
  • Create a sealed class called InternalAuditTransfer that inherits from BankTransaction. This class represents a sensitive system-level transfer that should never be modified or inherited from. Implement Execute() to print "Executing secure audit transfer..." and return true.
  • In your Main method, instantiate a Deposit and an InternalAuditTransfer and call Execute() on both.
  • To verify your understanding, try to create a class that inherits from InternalAuditTransfer and observe the compiler error.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.