Sobes.tech
Junior — Middle

How to implement the open-closed principle in object-oriented programming?

sobes.tech AI

Answer from AI

The Open/Closed Principle in object-oriented programming means that software entities (classes, modules, functions) should be open for extension but closed for modification. This means that the system's behavior can be extended without changing existing code.

This is implemented, for example, through the use of abstractions and inheritance. Instead of modifying an existing class, a new class is created that extends the functionality of the base.

Example in Java:

interface Shape {
    double area();
}

class Rectangle implements Shape {
    private double width, height;
    public Rectangle(double w, double h) { width = w; height = h; }
    public double area() { return width * height; }
}

class Circle implements Shape {
    private double radius;
    public Circle(double r) { radius = r; }
    public double area() { return Math.PI * radius * radius; }
}

// Now, to add a new shape, for example, a triangle, we create a new class without changing existing ones.

Thus, the extension of functionality occurs through adding new classes, not modifying existing ones.