[oop] encapsulation vs abstraction real world example

For an example of encapsulation i can think of the interaction between a user and a mobile phone. The user does not need to know the internal working of the mobile phone to operate, so this is called abstraction. But where does encapsulation fit in to this example? Could someone please shed some light on this?

This question is related to oop programming-languages

The answer is


Encapsulation is hiding information.

Abstraction is hiding the functionality details.

Encapsulation is performed by constructing the class. Abstraction is achieved by creating either Abstract Classes or Interfaces on top of your class.

In the example given in the question, we are using the class for its functionality and we don't care about how the device achieves that. So we can say the details of the phone are "abstracted" from us.

Encapsulation is hiding WHAT THE PHONE USES to achieve whatever it does; Abstraction is hiding HOW IT DOES it.-


Encapsulation helps in adhering to Single Responsibility principle and Abstraction helps in adhering to Code to Interface and not to implement.

Say I have a class for Car : Service Provider Class and Driver Class : Service Consumer Class.

For Abstraction : we define abstract Class for CAR and define all the abstract methods in it , which are function available in the car like : changeGear(), applyBrake().

Now the actual Car (Concrete Class i.e. like Mercedes , BMW will implement these methods in their own way and abstract the execution and end user will still apply break and change gear for particular concrete car instance and polymorphically the execution will happen as defined in concrete class.

For Encapsulation : Now say Mercedes come up with new feature/technology: Anti Skid Braking, while implementing the applyBrake(), it will encapsulate this feature in applyBrake() method and thus providing cohesion, and service consumer will still access by same method applyBrake() of the car object. Thus Encapsulation lets further in same concrete class implementation.


I guess an egg shell can be consider the encapsulation and the contents the abstraction. The shell protects the information. You cant have the contents of an egg without the shell.,,LOL


Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing

Abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system.

Consider the below real time example:

Encapsulation: As a driver you know how to start the car by pressing the start button and internal details of the starting operations are hidden from you. So the entire starting process is hidden from you otherwise we can tell starting operation is encapsulated from you.

OR

The driving wheel is encapsulated the process of rotating the wheel from you.

Abstraction:

Before mentioning anything about abstraction, we can take three different users here (I am calling them as entity)

1) You 2) Local Mechanic 3) Expert

You Entity: Since you know only to start the car by pressing a button and all other operations behind the scene are abstracted from you.

Local Mechanic Entity: Our local mechanic knows some of the implementation of starting the car, i.e. he can open car's bonnet and check the battery cable or chock etc. So in short Local Mechanic Entity knows some of the implementations of the car.

Expert Entity: Since our expert (Designer of the car) mechanic knows all the operations of our car, he can repair it very quickly. So in short Expert Entity knows all the implementations of the car.

The car's operation is completely abstracted from you and it is partially implemented to Local Mechanic Entity and fully implemented to Expert Entity. So you are an abstract class having only abstract methods, Local Mechanic Entity has extended You(Since he is also an ordinary user) and he implemented some of the methods and last our expert Entity extending Local Mechanic and implementing all the methods.

I think this is a good example.


I feel like encapsulation may make more sense to discuss when you see HOW NOT TO DO in programming. For example, consider a Car class as below.

 class Car{
   public float speed =0;
   public boolean isReverse = false;
   public boolean isStarted = false;
 }

The client code may use above car class as below.

class Main{
  public static void main(args String[]){
   Car car = new Car();
   // No need to start??
   car.speed = 100; // Turbo mode directly to 100
   car.speed = 0; // Turbo break
  }
}

See more at: http://brevitaz.com/encapsulation-example-benefits-java/

This is uncontrolled access to car speed and other variables. By encapsulation, Car class can have complete control over how the data variables within car class can be modified.

Any concrete entity that has some behavior is example of Encapsulation. The behavior is provided by wrapping up something and hiding something from client.In case of mobile, it is signals, chips, circuits, battery and so on.

For abstraction of the same example - normal user may say I am ok with anything using which I can make calls and receive calls. This abstraction can be substituted by any concrete mobile. Check out Abstraction examples.


In General words,Abstraction is Just Hiding the complex things behind a particular Procedure to make the procedure look simple.
Example:Monitor ON/OFF::--The user doesn't need to know much about all the chips functioning that happens when Monitor is switched ON or OFF..All he needs to know is On Function ON-Monitor is On and on function OFF-Monitor is off...

Or Better Look for a car--Everyone Knows that There's a special Gear machine Which changes the gear,nobody bother to know what all functionality undergoes for a gear to change..So,That's abstraction(avoiding unwanted implementations to prevent Complexity).

So,If a developer provides a good abstraction, users won't be tempted to peek at the object's internal mechanisms.

Abstraction is achieved by making class abstract having one or more methods abstract. Which is nothing but essential characteristic which should be implemented by the class extending it. e.g. when you inventing/designing a car you define a characteristics like car should have 4 doors, break, steering wheel etc… so anyone uses this design should include this characteristics. Implementation is not the head each of abstraction. It will just define characteristics which should be included.

Encapsulation is restricting a user to follow a particular procedure to access control of a particular process.It Just provides safety and ensures system robustness.

Example:We can consider The HR in a company as a person that works on the principle of Encapsulation.i.e. we cannot talk to other departments directly we need to communicate through them through HR.This ensures security and better maintenance of company's records.

Together we can take example of a UNDER CONSTRUCTION BUILDING..where we can say that things like 'no. of managers' required,Types of Materials,No of workers etc as abstraction as they need to there in every Building Construction.

But,at the same time,Inclusion of every such field into a CONTRACTOR which acts as a mediator between the workers and the Building-Investor can be looked upon as Encapsulation. As,It hides all the above properties into one Entity.

Hence If you would have understood till now you can say that abstraction is just a subset of ENCAPSULATION.i.e.Every entity that performs abstraction is encapsulated internally but every thing that shows encapsulation need not be abstraction always.

e.g. .ToString() Method defined in almost every class is implementation of Abstraction because We don't the functionaltiy Within,all we care is that it changes almost everything to string.And as it assembles a s a unit,it is encapsulated too..But,The private members that we hide and access through Properties is an example of encapsulation only as it is done basically keeping data security in mindd..!!

Hope This answers your Question..!!


Let me give my 2 cents of a real-world example-analogy close to IT.

Lets say you have a subscription site, e.g a wordpress site

Each user has a role, eg admin, subscriber and so on. Many users can be admins, subscribers etc..

So abstraction here is reflected in the fact that any user with admin role can do a set of things, it does not matter which specific user this is (this is an example of abstraction).

On the other hand, subscriber users do not have access to certain settings of the site, thus some internals of the application are encapsulated for plain subscribers (this is an example of encapsulation)

As one can see abstraction and encapsulation are relative concepts, they apply with respect to something specific.

One can follow this line of reasoning and explain polymoprhism and inheritance.

For example super-admin users could do all the things admin users could do, plus some more. Moreover, if admin roles get an update in functionality, super-admins would get the same update. Thus one can see here an example of inheritance, in that super-admin roles inherit all the properties of admin roles and extend them. Note that for most part of the site, admins are interchangeable with super-admins (meaning a super-admin user can easily be used in place of an admin user, but not vice-versa in general).


Abstration which hide internal detail to outside world for example you create a class(like calculator one of the class) but for end use you provide object of class ,With the help of object they will play and perform operation ,He does't aware what type of mechanism use internally .Object of class in abstract form .

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.For example class calculator which contain private methods getAdd,getMultiply .

Mybe above answer will help you to understand the concept .


Just think of Abstraction as hiding the keypad and display screen details, Encapsulation as hiding the internal circuitry that binds them.


Abstraction

It is used to manage complexities of OOPs. By using this property we can provide essential features of an object to the user without including its background explanations. For example, when sending message to a friend we simply write the message, say "hiiii" and press "send" and the message gets delivered to its destination (her,friend). Here we see abstraction at work, ie we are less concerned with the internal working of mobile that is responsible for sending and receiving message


Abstraction Means We focus on the essential qualities of some thing rather than one specific example and we automatically discard what is unimportant or irrelevant.

Example We are writing a bank account class,essential qualities of bank account are Opening date, Account title,Account number,Balance etc...

Encapsulation Means the idea of capsulation or surrounding some thing not just to keep the content together but also to protect and restrict form accessing out side.Along with secrecy It's about reducing dependencies between different parts of the application.

Example In our Bank account class Someone accessing the attribute of Balance and trying to change it ,Attempt can be successful if there is no encapsulation.


If you have seen important TV machine, TV connections and TV color tube is hidden inside the TV case which is not been exposed for viewers like us and exposed only neccessary things of a TV like TV Channel keys, TV volume keys, ON/OFF switch, Cable Switch and TV remote control for viewers to use it.This means TV machine, TV connections and TV color tube is an unwanted data and not needed for viewers to see is been hidden from outside the world

So encapsulation means hiding the important features of a class which is not been needed to be exposed outside of a class and exposing only necessary things of a class. Here hidden part of a class acts like Encapsulation and exposed part of a class acts like Abstraction.


Everything has many properties and behaviours so take whatever object you want TV, Mobile, Car, Human or anything.

Abstraction:

  1. Process of picking the essence of an object you really need
  2. In other words, pick the properties you need from the object Example:
    a. TV - Sound, Visuals, Power Input, Channels Input.
    b. Mobile - Button/Touch screen, power button, volume button, sim port.
    c. Car - Steering, Break, Clutch, Accelerator, Key Hole.
    d. Human - Voice, Body, Eye Sight, Hearing, Emotions.

Encapsulation:

  1. Process of hiding the details of an object you don't need
  2. In other words, hide the properties and operations you don't need from the object but are required for the object to work properly Example:
    a. TV - Internal and connections of Speaker, Display, Power distribution b/w components, Channel mechanism.
    b. Mobile - How the input is parsed and processed, How pressing a button on/off or changes volumes, how sim will connect to service providers.
    c. Car - How turning steering turns the car, How break slow or stops the car, How clutch works, How accelerator increases speed, How key hole switch on/of the car.
    d. Human - How voice is produced, What's inside the body, How eye sight works, How hearing works, How emotions generate and effect us.

ABSTRACT everything you need and ENCAPSULATE everything you don't need ;)


The wording of your question is odd - Abstraction vs Encapsulation? It should be - someone explain abstraction and encapsulation...

Abstraction is understanding the essence of the thing.

A real world example is abstract art. The artists of this style try to capture/paint the essence of the thing that still allows it to be the thing. This brown smear of 4 lines captures the essence of what a bull is.

Encapsulation is black boxing.

A cell phone is a great example. I have no idea how the cell phone connects to a satellite, tower, or another phone. I have no idea how the damn thing understands my key presses or how it takes and sends pictures to an email address or another phone number. I have no idea about the intricate details of most of how a modern smart phone works. But, I can use it! The phones have standard interfaces (yes - both literal and software design) that allows someone who understand the basics of one to use almost all of them.

How are the two related?

Both abstraction and encapsulation are underlying foundations of object oriented thought and design. So, in our cell phone example. The notion of a smart phone is an abstraction, within which certain features and services are encapsulated. The iPhone and Galaxy are further abstractions of the higher level abstraction. Your physical iPhone or Galaxy are concrete examples of multiple layers of abstractions which contain encapsulated features and services.


Abstraction

We use many abstractions in our day-to-day lives.Consider a car.Most of us have an abstract view of how a car works.We know how to interact with it to get it to do what we want it to do: we put in gas, turn a key, press some pedals, and so on. But we don't necessarily understand what is going on inside the car to make it move and we don't need to. Millions of us use cars everyday without understanding the details of how they work.Abstraction helps us get to school or work!

A program can be designed as a set of interacting abstractions. In Java, these abstractions are captured in classes. The creator of a class obviusly has to know its interface, just as the driver of a car can use the vehicle without knowing how the engine works.

Encapsulation

Consider a Banking system.Banking system have properties like account no,account type,balance ..etc. If someone is trying to change the balance of the account,attempt can be successful if there is no encapsulation. Therefore encapsulation allows class to have complete control over their properties.


Abstraction : you'll never buy a "device", but always buy something more specific : iPhone, GSII, Nokia 3310... Here, iPhone, GSII and N3310 are concrete things, device is abstract.

Encapsulation : you've got several devices, all of them have got a USB port. You don't know what kind of printed circuit there's back, you just have to know you'll be able to plug a USB cable into it.

Abstraction is a concept, which is allowed by encapsulation. My example wasn't the best one (there's no real link between the two blocks).

You can do encapsulation without using abstraction, but if you wanna use some abstraction in your projects, you'll need encapsulation.