Open/Closed Principle
This program demonstrates Open/Closed Principle.
Problem Statement
Write a Java program where new shapes can be added without modifying existing code.
Source Code
| 1 | interface Shape { double area(); } |
| 2 | class Circle implements Shape { |
| 3 | int r; Circle(int r){ this.r=r; } |
| 4 | public double area(){ return 3.14*r*r; } |
| 5 | } |
| 6 | class Rectangle implements Shape { |
| 7 | int w,h; Rectangle(int w,int h){ this.w=w; this.h=h; } |
| 8 | public double area(){ return w*h; } |
| 9 | } |
| 10 | public class OCPExample { |
| 11 | public static void main(String[] args) { |
| 12 | System.out.println("Eduinq OCP Example"); |
| 13 | Shape s=new Circle(5); |
| 14 | System.out.println("Area: "+s.area()); |
| 15 | } |
| 16 | } |
Program Output
Eduinq OCP Example Area: 78.5
Explanation
OCP states classes should be open for extension, closed for modification. - Adding new shapes requires no changes to existing code. - This promotes scalability and reduces risk of breaking existing functionality. Conclusion: Shows how to apply Open/Closed Principle.