Language: EN

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

What are and how to use sealed classes

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

You might wonder, Why would I want to prevent inheritance? Doesn’t it 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 undesired modification of a class.

clase-sellada

Your sealed and closed class forever

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

For example, imagine that I generate a library for a project, which manages payments for some clients. For that, I have my objects, all cute, very well done.

If someone else 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.

Since it is an important or critical process and I don’t want anyone to modify its behavior, either by mistake or intentionally, I will mark 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 does it according to its own approach.

Object-oriented languages like C++, C#, or Java have it natively, using a reserved word.

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

While dynamically typed languages like JavaScript or Python, due to their own implementation, suffer the most in capturing the concept.

Let’s see it with some examples

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

public sealed class Utilidades
{
    public void MetodoUtil()
    {
        Console.WriteLine("Método de utilidad");
    }
}

// This will generate a compilation error
public class SubUtilidades : Utilidades
{
}

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

class Utilidades final
{
public:
    void MetodoUtil() const {
        std::cout << "Método de utilidad" << std::endl;
    }
};

// This will generate a compilation error
class SubUtilidades : public Utilidades
{
};

In TypeScript, you can simulate the behavior of a sealed class using private constructors.

class Utilidades {
    private constructor() {}

    static metodoUtil(): void {
        console.log("Método de utilidad");
    }
}

// This will generate a compilation error
class SubUtilidades extends Utilidades {
}

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 Utilidades(metaclass=FinalMeta):
    def metodo_util(self):
        print("Método de utilidad")

# This will generate a runtime error
class SubUtilidades(Utilidades):
    pass