open closed principle in java explain with an example

Understanding Open-Closed Principle in Java: Example Explained

By Andrew Brown
AD

The Open-Closed Principle (OCP) is a fundamental SOLID principle in object-oriented design, introduced by Bertrand Meyer and further refined by Robert C. Martin. It advocates for 'closing a class for modification while keeping it open for extension,' significantly influencing how we structure our code. Let's delve into this principle, explore its significance in Java, and understand it through a practical example.

At the heart of OCP lies the strategy of making our software entities – classes, modules, functions – open for extension yet closed for modification. This promotes code extensibility, ease of use, and reduces bugs that might otherwise creep in during modification.

The essence of Open-Closed Principle in Java

In the context of Java, the Open-Closed Principle encourages the use of inheritance and composition over modification. It advocates for creating modules that can be extended without altering their source code. This leads to more stable and flexible codebases.

AD
Open Closed Principle Explained with Examples in Java
Open Closed Principle Explained with Examples in Java
Open and Closed Class Words in English | Definition | Examples | Differences
Open and Closed Class Words in English | Definition | Examples | Differences
Java OOP Concepts Explained | Class, Object, Encapsulation, Inheritance, Polymorphism & Abstraction
Java OOP Concepts Explained | Class, Object, Encapsulation, Inheritance, Polymorphism & Abstraction

Java inherently supports OCP through interfaces and abstract classes. By declaring methods and leaving their implementation open, we adhere to the OCP – the class is closed for modification, but open for extension via the interface's implementation.

OCP and Interfaces

Interfaces provide a clear example of the Open-Closed Principle. By defining method signatures and leaving their implementation open, interfaces encourage extension while being closed for modification.

Understanding Closures in JavaScript
Understanding Closures in JavaScript
The Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level
Liskov Substitution Principal explained with examples in Java
Liskov Substitution Principal explained with examples in Java

Consider the following example: defining a `Logger` interface in Java.

```java public interface Logger { void log(String message); } ```

This interface is open for extension, as any class can implement the `log` method. Simultaneously, it's closed for modification – adding or changing method signatures in the interface would require altering all implementing classes, counter to OCP.

AD

OCP and Abstract classes

Abstract classes also exemplify OCP. They provide a partial implementation, defining abstract methods that descendants must implement, thus being open for extension but closed for modification.

an open closed pringle diagram with several different types of words and numbers on it
an open closed pringle diagram with several different types of words and numbers on it
Java Loops Explained | for, while, do-while, Nested & for-each Loop (Java Series #6)
Java Loops Explained | for, while, do-while, Nested & for-each Loop (Java Series #6)
The Sliding Window Trick Every Coder Must Know
The Sliding Window Trick Every Coder Must Know
Mastering Object-Oriented Design with SOLID Principles in Java
Mastering Object-Oriented Design with SOLID Principles in Java
Open-close
Open-close
open×close
open×close

Let's illustrate this with a simple `Animal` abstract class:

```java public abstract class Animal { private String name; public Animal(String name) { this.name = name; } public abstract void makeSound(); public String getName() { return name; } } ```

The `makeSound` method is open for extension, but the class itself is closed for modification, apart from adding new fields or methods (which adhere to OCP).

AD

Practical demonstration of OCP in Java

Now let's consider a real-world scenario that employs OCP – creating a simple logging framework with different log levels, like `INFO`, `WARN`, `ERROR`, etc.

7 Common Java Errors Beginners Make (And How to Fix Them) | Java Programming Tips
7 Common Java Errors Beginners Make (And How to Fix Them) | Java Programming Tips
Java Methods Explained for Beginners | Java Methods Made Easy with Examples | Java Notes #4
Java Methods Explained for Beginners | Java Methods Made Easy with Examples | Java Notes #4
Java Continue Statement Explained | Loop Control Made Easy ☕
Java Continue Statement Explained | Loop Control Made Easy ☕
Web Development programing tricks and tips for beginners
Web Development programing tricks and tips for beginners
Best Java Training in Chennai|Java Course Chennai - Enroll Now
Best Java Training in Chennai|Java Course Chennai - Enroll Now
Cloning in Java | Shallow Copy and Deep Copy tutorial with examples
Cloning in Java | Shallow Copy and Deep Copy tutorial with examples
Open and closed signs. Vector illustration.
Open and closed signs. Vector illustration.
a purple screen with the text closure
a purple screen with the text closure
OOPS Concepts in Java – OOPS Concepts Example
OOPS Concepts in Java – OOPS Concepts Example
Java Collections Framework Explained | List, Set, Queue & Map (Beginner Guide) ☕
Java Collections Framework Explained | List, Set, Queue & Map (Beginner Guide) ☕
Java OOPS Concepts – Important Notes
Java OOPS Concepts – Important Notes
Avoid Closing the Form in Java
Avoid Closing the Form in Java
Logical Operators in Java: Think Smarter, Code Better ☕🚀
Logical Operators in Java: Think Smarter, Code Better ☕🚀

We can create an abstract `LogLevel` class and concrete implementations for each log level. This design enables adding new log levels without modifying the existing codebase.

```java public abstract class LogLevel { public abstract void log(String message); } // INFO, WARN, and ERROR classes extend LogLevel, implementing their log behavior public class InfoLogLevel extends LogLevel { @Override public void log(String message) { System.out.println("INFO: " + message); } } ```

By following OCP, we maintain a stable logging framework that we can easily extend with new log levels without modifying the existing code.

AD

In conclusion, applying the Open-Closed Principle in Java leads to more stable, flexible, and extensible code. By leveraging interfaces and abstract classes, we can keep our code 'closed for modification yet open for extension,' fostering a robust and maintainable codebase. Embrace OCP in your next Java project and experience the benefits firsthand!"

AD