Most of people consider encapsulation feature of object oriented programming as data hiding. But Encapsulation stands for few more features. Suppose we have a Vehicle registration software. Which has following properties,
- Vehicle has a engine/chesis number
- Vehicle may have door
- Vehicle have wheels
- Vehicle can be different type: Bus, Car, Bike
Suppose we have a Abstract Vehicle
Class public abstract class Vahicle {
public abstract String getChesisNumber();
public int getNumberOfDoor() {}
public abstract int getNumberOfWheel();
}
Now Bus, Car, Bike extend Vehicle
public abstract class Bus extends Vehicle {
public int getNumberOfDoor() {}
}public abstract class Car extends Vehicle
{
public int getNumberOfDoor() {
return 4;
}
public abstract class Bike extends Vehicle { }
Now a Car can be a Private car or Taxi so
public PrivateCar extends Car {
public String getChesisNumber() {
return "CN354656565";
}
public int getNumberOfWheel(){
return 4;
}
}
Suppose we have a special type of Air Conditioned Taxi named ClassicTaxi
public ClassicTaxi {
public String getEngineNumber(){
return "CN35465655498";
}
public int getTotalNumberOfWheel(){
return 4;
}
}
Only the Taxi know about this
public Taxi extends Car {
private ClassicTaxi ct;
public String getChesisNumber(){
return ct.getEngineNumber();
}
public int getNumberOfWheel(){
return ct.getTotalNumberOfWheel();
}
Now you can notice the different levels of Encapsulation in this example.
- Encapsulation of Data: Bus, Bike and PrivateCar and Taxi are encapsulation from everything
- Encapsulation of Type: Client of Vehicle do not know about Bus, Car and Bike
- Encapsulation of Method:
getNumberOfDoor() of Bus and Car are hidden from all - Encapsulation of Object: Only Taxi is aware abot Classic Taxi
So as we can see. Its not only bounded to the hiding data but also hiding type, method as well as object too. There is land mark theory described in the book of Gang of Four(GOF) “Consider what should be variable in your design. This approach is the opposite of focusing on the causes of redesign. Instead of considering what might force a change to a design, consider what you want to be able to change without redesign. The focus here is on encapsulating the concept that varies, a theme of many design patterns.”(Ref 1) The Book of Shalloway define this simply as “Find what varies and encapsulate it.” (Ref 2).
References:
1. Design Pattern: Elements of Reusable Object-Oriented Software
2. Design Pattern Explained: A new perspective on Object Oriented Design
By: Md. Shahjalal
Posted by Md. Shahjalal 
