top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to explain difference between encapsulation and abstraction in java to an interviewer?

+3 votes
614 views
How to explain difference between encapsulation and abstraction in java to an interviewer?
posted Feb 4, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Encapsulation: A simple definition of encapsulation is - combining the data (information) and the methods (functions) that can manipulate that data into one capsule (class/object). Depending on how you write program encapsulation, it guarantees that the encapsulated data is not accessed by any other function/method/program outside the encapsulated object. For example,

class MyCapsule
{ 
private:
int myInt;
char myChar;
public:
MyIntFunc() { myInt = 10; }
MyCharFunc() { myChar = 'A'};
};

In this case, no other program/function/method can access myInt other than MyIntFunc. Same is true for myChar and MyCharFunc.

Abstraction: A simple definition of abstraction is to hide actual implementation of an object from the external world that would use the object. For example, a program that is drawing circles and squares using those objects need not know how those objects are implemented. It is enough for the program to know what the behavior of these objects is, and how to use these objects (rather than how these objects are implemented internally).

So, drawing a parallel between abstraction and encapsulation, when you encapsulate data and methods that operate on data into one object, the external program that uses this object need not know the internal workings of the object to use the object. Thus making the object abstract data type to the external program. Classic examples of abstract data type in C (yes) are int, char, float, double etc. Classes are OOPL variations and extensions of the traditional abstract data types.

answer Feb 4, 2015 by Shyam
...