Mar 19, 2013

Abstraction Vs Encapsulation

Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s). Abstraction is providing a generalization (say, over a set of behaviors). Encapsulation: Is hiding unwanted/un-expected/propriety implementation details from the actual users of object. e.g. List list = new List(); list.Sort(); /* Here, which sorting algorithm is used and hows its implemented is not useful to the user who wants to perform sort, that's why its hidden from the user of list. */ Abstraction: Is a way of providing generalization and hence a common way to work with objects of vast diversity. e.g. class Aeroplane : IFlyable, IFuelable, IMachine { // Aeroplane's Design says: // Aeroplane is a flying object // Aeroplane can be fueled // Aeroplane is a Machine } // But the code related to Pilot, or Driver of Aeroplane is not bothered // about Machine or Fuel. Hence, // pilot code: IFlyable flyingObj = new Aeroplane(); flyingObj.Fly(); // fighter Pilot related code IFlyable flyingObj2 = new FighterAeroplane(); flyingObj2.Fly(); // UFO related code IFlyable ufoObj = new UFO(); ufoObj.Fly(); // **All the 3 Above codes are genaralized using IFlyable, // Interface Abstraction** // Fly related code knows how to fly, irrespective of the type of // flying object they are. // Similarly, Fuel related code: // Fueling an Aeroplane IFuelable fuelableObj = new Aeroplane(); fuelableObj.FillFuel(); // Fueling a Car IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { } fuelableObj2.FillFuel(); // ** Fueling code does not need know what kind of vehicle it is, so far // as it can Fill Fuel**

No comments: