Open Closed Design Principle Java

The open closed design principle says that software entities like classes, modules, functions, etc. should be open for extension, but closed for modification. It is a SOLID design principle and represent “O” on the SOLID acronym.

A class is considered to be closed if changes are guaranteed to not happen. It can be used as a base class which can be extended by child classes.

A class is considered to be open if its functionality can be enhanced by its subclasses.

Let us understand the open closed design principle with below example. Consider a case when we need to calculate areas of various shapes. We start with creating a class for our first shape Rectangle.

```public class Rectangle{ public double length; public double width; }```

Next create a class to calculate area of this Rectangle which has a method calculateRectangleArea().

```public class AreaCalculator{ public double calculateRectangleArea(Rectangle rectangle){ return rectangle.length *rectangle.width; } }```

Now we have circle as a new shape. So we create a Circle class.

```public class Circle{ public double radius; }```

Then we modify AreaCalculator class to add circle calculations through a new method calculateCircleArea().

```public class AreaCalculator{ public double calculateRectangleArea(Rectangle rectangle){ return rectangle.length *rectangle.width; } public double calculateCircleArea(Circle circle){ return (22/7)*circle.radius*circle.radius; } }```

Whenever a new requirement comes we have to modify our class so this design is not closed for modification.

Better Solution:
First we will create a base type shape which will be implemented by all shapes. It has an abstract method calculateArea(). Every sub class override this method and will provide own implementation. This design follow the open closed design principle as Shape class is open for extension and closed for modification.

```public interface Shape{ public double calculateArea(); }   public class Rectangle implements Shape{ double length; double width; public double calculateArea(){ return length * width; } }   public class Circle implements Shape{ public double radius; public double calculateArea(){ return (22/7)*radius*radius; } }```