OCP in Shape System

This program applies OCP to shape system.

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 OCPShape {
11 public static void main(String[] args) {
12 System.out.println("Eduinq OCP Shape");
13 Shape s=new Rectangle(5,10);
14 System.out.println("Area: "+s.area());
15 }
16 }

Program Output

Eduinq OCP Shape
Area: 50.0

Explanation

OCP allows extension by adding new shapes. - Existing code remains unchanged. - This ensures scalability and robustness in larger systems. Conclusion: Shows OCP applied to shape system.

Quick Links to Explore