Language: EN

que-es-una-clase-sellada-en-programacion

What are and how to use sealed classes

Sealed classes, or final classes, are classes that cannot be inherited by other classes, ensuring that certain classes are not extended or modified.

You may ask yourself, why would I want to prevent inheritance? Doesn’t that go against the principles of object-oriented programming design?

The main reason is for security. Declaring a class as sealed serves to protect the software design from unwanted modifications to a class.

clase-sellada

Your sealed class and closed forever

This is particularly useful in frameworks and libraries, where the framework developer wants to prevent users from modifying critical components.

For example, imagine I create a library for a project that manages customer payments. For which I have my objects, all neat and well-made.

If another person takes one of my classes, inherits it, modifies its behavior, and returns it to the library, the rest of the objects will “swallow” it. Because that’s how Polymorphism works.

As this is an important or critical process and I don’t want someone to accidentally or intentionally modify its behavior, I will mark the important classes as sealed.

Examples in different languages

The topic of sealed or final classes is one of the least standardized among different programming languages, and each one does it according to its own approach.

More object-oriented languages, such as C++, C# or Java have it natively, using a reserved keyword.

Other languages like Kotlin have all methods sealed by default, and they must be explicitly opened with the reserved keyword Open.

While dynamically typed languages, like JavaScript or Python, due to their own implementation, suffer the most when it comes to adopting the concept.

Let’s see it with some examples

In C#, a sealed class is declared using the sealed keyword.

public sealed class Utilities
{
    public void UtilityMethod()
    {
        Console.WriteLine("Utility method");
    }
}

// This will generate a compilation error
public class SubUtilities : Utilities
{
}

In C++, sealed classes can be achieved using the final keyword.

class Utilities final
{
public:
    void UtilityMethod() const {
        std::cout << "Utility method" << std::endl;
    }
};

// This will generate a compilation error
class SubUtilities : public Utilities
{
};

In TypeScript, the behavior of a sealed class can be simulated using private constructors.

class Utilities {
    private constructor() {}

    static utilityMethod(): void {
        console.log("Utility method");
    }
}

// This will generate a compilation error
class SubUtilities extends Utilities {
}

In Python, sealed classes are not directly supported, but their behavior can be simulated using metaclasses.

class FinalMeta(type):
    def __new__(cls, name, bases, dct):
        if any(isinstance(base, FinalMeta) for base in bases):
            raise TypeError(f"Cannot inherit from final class {bases}")
        return super().__new__(cls, name, bases, dct)

class Utilities(metaclass=FinalMeta):
    def utility_method(self):
        print("Utility method")

# This will generate a runtime error
class SubUtilities(Utilities):
    pass