Junior — Middle
What is meant by the principle of openness/closedness 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, reducing the risk of errors and simplifying maintenance.
For example, if you need to add new functionality, it is better to create a new class that extends the existing one rather than changing the original class directly. In C++, this is often achieved through inheritance and polymorphism:
class Shape {
public:
virtual double area() const = 0; // abstract method
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override { return width * height; }
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};
If you need to add a new shape, for example, a triangle, simply create a new Triangle class without changing existing classes.