I know that open closed principle mean open for extension and closed for modification. Consider an example as follows
public class Vehicle{
public void service(){
//vehicle servicing code
}
}
public class Bike extends Vehicle{
public void service(){
// bike specific servicing
}
}
Now I understand that Bike
class has extended Vehicle
and adds new functionality using Open Closed Principle.
Consider I create jar file of Vehicle
class and then Bike
class extends Vehicle
class from jar. In this case, we can't modify Vehicle
class and Bike
extends it. Is it a good example of open closed principle?
I would like to know how OCP is different from inheritance
OCP is not different from Inheritance, rather the "Open" part of the OCP is open for extension, but should be closed for modification. I.e. the code should only modified for errors/bugs but for new extension or change to the functionality it should be extended.
As a Side note I believe this would be better put in the programmers.stackexchange.com site.