The Open-Closed Principle states that:
Software entities (classes, modules, functions, etc) should be open for extension, but closed for modification.
This principle basically states that we have to design our modules, classes, and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code
Now let us discuss the Open-Closed Principle in the following example.
Let us assume we are trying to calculate the area of some shapes. So let's take the example of a rectangle and a circle. The classes for these have been formed in the following code:
public class Rectangle {
private double length;
private double height;
// getters/setters ...
}
public class Circle {
private double radius;
// getters/setters ...
}
So a common function used...