Open Closed Principle

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We know that building a great software requires application of design principles. A design principle is a concept that is applied when designing or writing code to make it more flexible, maintainable and extensible. It helps in flexible, maintainable and extensible software. This article will deal with one of them i.e . Open Closed Principle

Open Closed Principle:

In short, Open Closed Principle tells us “You should not modify existing behavior but if you want, you can extend it according to your needs.” i.e. Code is open for extension but closed for modification. 


Consider we have a Vehicle class and a Mechanic class. A mechanic can service all vehicles. You are the owner of Vehicle class and your code does vehicle servicing well. The mechanic simply calls service method in Vehicle class to get it done. Here is how a mechanic services a vehicle.




This simply prints

Nothing fancy about it, a simple call to method on object. Now there is a customer who owns a specific bike of which servicing needs more attention and more tasks than a general vehicle servicing. The mechanic wants to service the bike and he asks you to change code in service() method to make it bike specific.

Now you have a problem, you cannot change service method in Vehicle class to make it bike specific.So here comes the open closed principle in action. You can ask the mechanic to extend existing Vehicle class and override service method to write bike specific code in it. In this manner Vehicle class code is not modified and mechanic creates Bike class extending Vehicle to add bike servicing specific code.



our problem is solved, we did not have to modify Vehicle class and mechanic can extend Vehicle class functionality by inheriting it. I hope this article helped understand the open closed principle



Share Button

2 comments for “Open Closed Principle

  1. fakhruddin
    May 9, 2016 at 12:20 am

    amazing blog dude. please write about Threads also.

    • May 9, 2016 at 8:47 am

      Thank you for your kind words, I will surely keep updating.

Leave a Reply

Your email address will not be published. Required fields are marked *