Difference in Information hiding and data abstraction? - oop

Is there any difference in Data Abstraction and Information hiding? After going through all the answers in this link I am more confused.
Abstraction VS Information Hiding VS Encapsulation
Couldn't find any difference. Is it just that we can call one (info hiding) as a goal & the other (abstraction) as a process? But this is no satisfactory difference for me. Further, I got that encapsulation is the technique to implement the process of abstraction Am I right here? Please explain the exact difference.

Information hiding is when the designer specifically decides to limit access to details of an implementation. It's a principle that's older than object-oriented design, but is often used.
A simple example is defining constants in C, e.g., #define NAME_SIZE 15 The code (clients) of the constant don't need to know its value, and won't be troubled if you (the designer) decide to change its value later. They shouldn't make assumptions about the fact that it's really 15, because you might decide to change it.
Abstraction is when you're dealing with an aggregate, e.g., a Car is an abstraction of details such as a Chassis, Motor, Wheels, etc. Abstractions allow us to think of complex things in a simpler way.
Encapsulation is how we decide the level of detail of the elements comprising our abstractions. Good encapsulation applies information hiding, to enforce limits of details. For example, my Car is comprised in reality of all its parts, yet it only provides to me (the driver) an interface that's appropriate for my needs and not more. I can control the doors, locks, windows, lights, horn, sunroof, the direction of the movement, accelerate, decelerate, etc. Even though I might be curious to manipulate the details of the "how" of all these things, encapsulation prevents me from seeing more.
If my car's implementation changes (I change from a combustion engine to an electric or hybrid), because I as the driver know only the limited interface, I don't need to change how I drive the car. Abstraction allows me to just know I'm driving a car, instead of hundreds of pieces of metal, rubber, etc.
An example of where information hiding was not part of a car might be a choke valve. My parents told me how those used to work in the cars they drove... it was a combustion-engine detail, which would not be useful in an electric car.

Data hiding is the process by which access modifiers are used to hide the visibility of java methods and variables. They access modifiers are: public, private and protected.
Abstraction is the process by which we define a specific behavior by beans of abstract classes and methods which form the skeleton for any class that would be extending this class.

"Information hiding" is an important PART of "Data abstraction", but not the whole concept.
And remember: you can (and should) have "information hiding" in procedural code (like "don't use globals", etc in FORTRAN or BASIC) - but you won't necessary have an "abstract data type".
Information hiding and Abstract Data Types are closely related, but they are different concepts.

A class normally hides its implementation details from its clients. This is called information hiding. by creating interfaces we summon information hiding concept...
example of information hiding is below...
we have a interface in our header file...
class Coder
{
public:
Coder();
void prints();
private:
int x;
};
and implementation of functions in another file "Coder.cpp" is...
Coder::Coder
{
x=10;//any int value you can take;
}
void Coder::prints()
{
cout<<x;
}
rather tahn doing above in two files (one header+one cpp file) we could have done it at a single place. we could have given defination of constructor and print function in header file itself...
class Coder
{
public:
Coder()
{
x=10;//any int value you can take;
}
void prints()
{
cout<<x;
}
private:
int x;
};
if we have done this we were not able to implement information hiding... and our client will know how we have implemented our functions!
for data absraction you can consider... example of stacks...
A client of a stack class need not be concerned with the stack's implementation. The client knows only that when data items are placed in the stack, they will be recalled in last-in, first-out order. The client cares about what functionality a stack offers, not about how that functionality is implemented. This concept is referred to as data abstraction.

Abstraction is the representation of something with less details (as in an abstract painting). In OO, an abstract type can be manipulated without committing to its internal representation. For example, Telephone Number as an abstraction of a telephone number can be operated on without the client knowing that it consists of country code, area code, and the actual number. Abstraction is most useful in the analysis and design phase because it allows you to talk in terms of the abstract data type (eg. Telephone Number) without having to worry how it will be implemented.
A more familiar type, string is an abstraction of text: you manipulate string without knowing how it is implemented. The string abstraction allows its internals to be changed without affecting its usage in an application design.
Information hiding and encapsulation are two ways in which an abstract data type might be implemented. An abstract data type might not even have to hide its internal state or its encapsulation; for example, Number as an abstraction may be implemented as an int.

Related

What's the difference between abstraction and encapsulation?

In interviews I have been asked to explain the difference between abstraction and encapsulation. My answer has been along the lines of
Abstraction allows us to represent complex real world in simplest manner. It is the process of identifying the relevant qualities and behaviors an object should possess; in other words, to represent the necessary feature without representing the background details.
Encapsulation is a process of hiding all the internal details of an object from the outside real world. The word "encapsulation", is like "enclosing" into a "capsule". It restricts clients from seeing its internal view where the behavior of the abstraction is implemented.
I think with above answer the interviewer was convinced, but then I was asked, if the purpose of both is hiding, then why there is a need to use encapsulation. At that time I didn't have a good answer for this.
What should I have added to make my answer more complete?
Abstraction has to do with separating interface from implementation. (We don't care what it is, we care that it works a certain way.)
Encapsulation has to do with disallowing access to or knowledge of internal structures of an implementation. (We don't care or need to see how it works, only that it does.)
Some people do use encapsulation as a synonym for abstraction, which is (IMO) incorrect. It's possible that your interviewer thought this. If that is the case then you were each talking about two different things when you referred to "encapsulation."
It's worth noting that these concepts are represented differently in different programming languages. A few examples:
In Java and C#, interfaces (and, to some degree, abstract classes) provide abstraction, while access modifiers provide encapsulation.
It's mostly the same deal in C++, except that we don't have interfaces, we only have abstract classes.
In JavaScript, duck typing provides abstraction, and closure provides encapsulation. (Naming convention can also provide encapsulation, but this only works if all parties agree to follow it.)
Its Simple!
Take example of television - it is Encapsulation, because:
Television is loaded with different functionalies that i don't know because they are completely hidden.
Hidden things like music, video etc everything bundled in a capsule that what we call a TV
Now, Abstraction is When we know a little about something and which can help us to manipulate something for which we don't know how it works internally.
For eg:
A remote-control for TV is abstraction, because
With remote we know that pressing the number keys will change the channels. We are not aware as to what actually happens internally. We can manipulate the hidden thing but we don't know how it is being done internally.
Programmatically, when we can acess the hidden data somehow and know something.. is Abstraction .. And when we know nothing about the internals its Encapsulation.
Without remote we can't change anything on TV we have to see what it shows coz all controls are hidden.
Abstraction
Exposing the Entity instead of the details of the entity.
"Details are there, but we do not consider them. They are not required."
Example 1:
Various calculations:
Addition, Multiplication, Subtraction, Division, Square, Sin, Cos, Tan.
We do not show the details of how do we calculate the Sin, Cos or Tan. We just Show Calculator and it's various Methods which will be, and which needs to be used by the user.
Example 2:
Employee has:
First Name, Last Name, Middle Name. He can Login(), Logout(), DoWork().
Many processes might be happening for Logging employee In, such as connecting to database, sending Employee ID and Password, receiving reply from Database. Although above details are present, we will hide the details and expose only "Employee".
Encapsulation
Enclosing. Treating multiple characteristics/ functions as one unit instead of individuals.
So that outside world will refer to that unit instead of it's details directly.
"Details are there, we consider them, but do not show them, instead we show what you need to see."
Example 1:
Instead of calling it as Addition, Subtraction, Multiplication, Division, Now we will call it as a Calculator.
Example 2:
All characteristics and operations are now referred by the employee, such as "John". John Has name. John Can DoWork(). John can Login().
Hiding
Hiding the implemention from outside world.
So that outside world will not see what should not be seen.
"Details are there, we consider them, but we do not show them. You do not need to see them."
Example 1:
Your requirement: Addition, Substraction, Multiplication, Division. You will be able to see it and get the result.
You do not need to know where operands are getting stored. Its not your requirement.
Also, every instruction that I am executing, is also not your requirement.
Example 2:
John Would like to know his percentage of attendance. So GetAttendancePercentage() Will be called.
However, this method needs data saved in database. Hence it will call FetchDataFromDB(). FetchDataFromDB() is NOT required to be visible to outside world.
Hence we will hide it. However, John.GetAttendancePercentage() will be visible to outside world.
Abstraction, encapsulation and hiding complement each others.
Because we create level of abstraction over details, the details are encapsulated. And because they are enclosed, they are hidden.
Difference between Abstraction and Encapsulation :-
Abstraction
Abstraction solves the problem in the design level.
Abstraction is used for hiding the unwanted data and giving relevant data.
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction- Outer layout, used in terms of design.
For Example:-
Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.
Encapsulation
Encapsulation solves the problem in the implementation level.
Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
Encapsulation means hiding the internal details or mechanics of how an object does something.
Encapsulation- Inner layout, used in terms of implementation.
For Example:- Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits.
Encapsulation
Encapsulation from what you have learnt googling around, is a concept of combining the related data and operations in a single capsule or what we could say a class in OOP, such that no other program can modify the data it holds or method implementation it has, at a particular instance of time. Only the getter and setter methods can provide access to the instance variables.
Our code might be used by others and future up-gradations or bug fixes are liable. Encapsulation is something that makes sure that whatever code changes we do in our code doesn't break the code of others who are using it.
Encapsulation adds up to the maintainability, flexibility and extensibility of the code.
Encapsulation helps hide the implementation behind an interface.
Abstraction
Abstraction is the process of actually hiding the implementation behind an interface. So we are just aware of the actual behavior but not how exactly the think works out internally. The most common example could the scenario where put a key inside the lock and easily unlock it. So the interface here is the keyhole, while we are not aware of how the levers inside the lock co-ordinate among themselves to get the lock unlocked.
To be more clear, abstraction can be explained as the capability to use the same interface for different objects. Different implementations of the same interface can exist, while the details of every implementation are hidden by encapsulation.
Finally, the statement to answer all the confusions until now -
The part that is hidden relates to encapsulation while the part that is exposed relates to abstraction.
Read more on this here
Abstraction : Abstraction is process in which you collect or gather relevant data and remove non-relevant data. (And if you have achieved abstraction, then encapsulation also achieved.)
Encapsulation: Encapsulation is a process in which you wrap of functions and members in a single unit. Means You are hiding the implementation detail. Means user can access by making object of class, he/she can't see detail.
Example:
public class Test
{
int t;
string s;
public void show()
{
s = "Testing";
Console.WriteLine(s);
Console.WriteLine(See()); // No error
}
int See()
{
t = 10;
return t;
}
public static void Main()
{
Test obj = new Test();
obj.Show(); // there is no error
obj.See(); // Error:- Inaccessible due to its protection level
}
}
In the above example, User can access only Show() method by using obj, that is Abstraction.
And See() method is calling internally in Show() method that is encapsulation, because user doesn't know what things are going on in Show() method.
I know there are lot's of answers before me with variety of examples.
Well here is my opinion abstraction is getting interested from reality .
In abstraction we hide something to reduce the complexity of it
and In encapsulation we hide something to protect the data.
So we define encapsulation as wrapping of data and methods in single entity referred as class.
In java we achieve encapsulation using getters and setters not just by wrapping data and methods in it. we also define a way to access that data.
and while accessing data we protect it also. Techinical e.g would be to define a private data variable call weight.Now we know that weight can't be zero or less than zero in real world scenario. Imagine if there are no getters and setters someone could have easily set it to a negative value being public member of class.
Now final difference using one real world example,
Consider a circuit board consisting of switches and buttons.
We wrap all the wires into a a circuit box, so that we can protect someone by not getting in contact directly(encapsulation).
We don't care how those wires are connected to each other we just want an interface to turn on and off switch. That interface is provided by buttons(abstraction)
Encapsulation : Suppose I have some confidential documents, now I hide these documents inside a locker so no one can gain access to them, this is encapsulation.
Abstraction : A huge incident took place which was summarised in the newspaper. Now the newspaper only listed the more important details of the actual incident, this is abstraction. Further the headline of the incident highlights on even more specific details in a single line, hence providing higher level of abstraction on the incident. Also highlights of a football/cricket match can be considered as abstraction of the entire match.
Hence encapsulation is hiding of data to protect its integrity and abstraction is highlighting more important details.
In programming terms we can see that a variable may be enclosed is the scope of a class as private hence preventing it from being accessed directly from outside, this is encapsulation. Whereas a a function may be written in a class to swap two numbers. Now the numbers may be swapped in either by either using a temporary variable or through bit manipulation or using arithmetic operation, but the goal of the user is to receive the numbers swapped irrespective of the method used for swapping, this is abstraction.
Abstraction: In case of an hardware abstraction layer, you have simple interfaces to trigger the hardware (e.g. turn enginge left/right) without knowing the hardware details behind. So hiding the complexity of the system. It's a simplified view of the real world.
Encapsulation: Hiding of object internals. The object is an abstraction of the real world. But the details of this object (like data structures...) can be hidden via encapsulation.
Abstraction refers to the act of representing essential features without including the background details or explanations.
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.
Difference between abstraction and encapsulation
1.Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
2.Abstraction solves the problem in the design side while Encapsulation is the Implementation.
3.Encapsulation is the deliverable of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
ABSTRACTION:"A view of a problem that extracts the essential information
relevant to a particular purpose and ignores the remainder of
the information."[IEEE, 1983]
ENCAPSULATION: "Encapsulation or equivalently information hiding refers to the
practice of including within an object everything it needs, and
furthermore doing this in such a way that no other object need ever
be aware of this internal structure."
Abstraction is one of the many benefits of Data Encapsulation. We can also say Data Encapsulation is one way to implement Abstraction.
My opinion of abstraction is not in the sense of hiding implementation or background details!
Abstraction gives us the benefit to deal with a representation of the real world which is easier to handle, has the ability to be reused, could be combined with other components of our more or less complex program package. So we have to find out how we pick a complete peace of the real world, which is complete enough to represent the sense of our algorithm and data. The implementation of the interface may hide the details but this is not part of the work we have to do for abstracting something.
For me most important thing for abstraction is:
reduction of complexity
reduction of size/quantity
splitting of non related domains to clear and independent components
All this has for me nothing to do with hiding background details!
If you think of sorting some data, abstraction can result in:
a sorting algorithm, which is independent of the data representation
a compare function, which is independent of data and sort algorithm
a generic data representation, which is independent of the used algorithms
All these has nothing to do with hiding information.
In my view encapsulation is a thought of programmer to hide the complexity of the program code by using access specifier.
Where as Abstraction is separation of method and object according to there function and behavior. For example Car has sheets, wheels, break, headlight.
Developer A, who is inherently utilising the concept of abstraction will use a module/library function/widget, concerned only with what it does (and what it will be used for) but not how it does it. The interface of that module/library function/widget (the 'levers' the Developer A is allowed to pull/push) is the personification of that abstraction.
Developer B, who is seeking to create such a module/function/widget will utilise the concept of encapsulation to ensure Developer A (and any other developer who uses the widget) can take advantage of the resulting abstraction. Developer B is most certainly concerned with how the widget does what it does.
TLDR;
Abstraction - I care about what something does, but not how it does it.
Encapsulation - I care about how something does what it does such that others only need to care about what it does.
(As a loose generalisation, to abstract something, you must encapsulate something else. And by encapsulating something, you have created an abstraction.)
Encapsulation is basically denying the access to the internal implementation or knowledge about internals to the external world, while Abstraction is giving a generalized view of any implementation that helps the external world to interact with it
The essential thing about abstraction is that client code operates in terms of a different logical/abstract model. That different model may be more or less complex than the implementation happens to be in any given client usage.
For example, "Iterator" abstracts (aka generalises) sequenced traversal of 0 or more values - in C++ it manifests as begin(), */-> (dereferencing), end(), pre/post ++ and possibly --, then there's +, +=, [], std::advance etc.. That's a lot of baggage if the client could say increment a size_t along an array anyway. The essential thing is that the abstraction allows client code that needs to perform such a traversal to be decoupled from the exact nature of the "container" or data source providing the elements. Iteration is a higher-level notion that sometimes restricts the way the traversal is performed (e.g. a forward iterator can only advance an element at a time), but the data can then be provided by a larger set of sources (e.g. from a keyboard where there's not even a "container" in the sense of concurrently stored values). The client code can generally switch to another data source abstracted through its own iterators with minimal or even no changes, and even polymorphically to other data types - either implicitly or explicitly using something like std::iterator_traits<Iterator>::value_type available.
This is quite a different thing from encapsulation, which is the practice of making some data or functions less accessible, such that you know they're only used indirectly as a result of operations on the public interface. Encapsulation is an essential tool for maintaining invariants on an object, which means things you want to keep true after every public operation - if client code could just reach in and modify your object then you can't enforce any invariants. For example, a class might wrap a string, ensuring that after any operation any lowercase letters were changed to upper case, but if the client code can reach in and put a lowercase letter into the string without the involvement of the class's member functions, then the invariant can't be enforced.
To further highlight the difference, consider say a private std::vector<Timing_Sample> data member that's incidentally populated by operations on the containing object, with a report dumped out on destruction. With the data and destructor side effect not interacting with the object's client code in any way, and the operations on the object not intentionally controlling the time-keeping behaviour, there's no abstraction of that time reporting functionality but there is encapsulation. An example of abstraction would be to move the timing code into a separate class that might encapsulate the vector (make it private) and just provide a interface like add(const Timing_Sample&) and report(std::ostream&) - the necessary logical/abstract operations involved with using such instrumentation, with the highly desirable side effect that the abstracted code will often be reusable for other client code with similar functional needs.
In my opinion, both terms are related in some sense and sort of mixed into each other. "Encapsulation" provides a way to grouping related fields, methods in a class (or module) to wrap the related things together. As of that time, it provides data hiding in two ways;
Through access modifiers.
Purely for hiding state of the class/object.
Abstracting some functionalities.
a. Through interfaces/abstract classes, complex logic inside the encapsulated class or module can be abstracted/generalized to be used by outside.
b. Through function signatures. Yes, even function signatures example of abstracting. Because callers only knows the signature and parameters (if any) and know nothing about how the function is carried out. It only cares of returned value.
Likewise, "Abstraction" might be think of a way of encapsulation in terms of grouping/wrapping the behaviour into an interface (or abstract class or might be even a normal class ).
As far as iOS is concerned, it can be said that Objective C files (i.e. .h and .m) use abstraction as well as encapsulation.
Abstraction
Header file (.h) only exposes the functions and public members to outside world. No one knows how they are used unless they have the implementation file with them. It is the .m file that holds all the usage and implementation logic with it self. "Implementation remains unexposed".
Encapsulation
The property (#property) encapsulates the memory management attribute (atomic, strong, retain, weak) of an iVar.
A program has mainly two parts : DATA and PROCESS. abstraction hides data in process so that no one can change. Encapsulation hides data everywhere so that it cannot be displayed.
I hope this clarifies your doubt.
Encapsulation is used for 2 main reasons:
1.) Data hiding & protecting (the user of your class can't modify the data except through your provided methods).
2.) Combining the data and methods used to manipulate the data together into one entity (capsule).
I think that the second reason is the answer your interviewer wanted to hear.
On the other hand, abstraction is needed to expose only the needed information to the user, and hiding unneeded details (for example, hiding the implementation of methods, so that the user is not affected if the implementation is changed).
Abstraction: Hiding the data.
Encapsulation: Binding the data.
Why Encapsulation? Why Abstraction?
lets start with the question below:
1)What happens if we allow code to directly access field ? (directly allowing means making field public)
lets understand this with an example,
following is our BankAccount class and following is its limitation
*Limitation/Policy* : Balance in BankAccount can not be more than 50000Rs. (This line
is very important to understand)
class BankAccount
{
**public** double balanceAmount;
}
Following is **AccountHolder**(user of BankAccount) class which is consumer of
**BankAccount** class.
class AccountHolder
{
BankAccount mybankAccount = new BankAccount();
DoAmountCreditInBankAccount()
{
mybankAccount.balanceAmount = 70000;
/*
this is invalid practice because this statement violates policy....Here
BankAccount class is not able to protect its field from direct access
Reason for direct access by acount holder is that balanceAmount directly
accessible due to its public access modifier. How to solve this issue and
successfully implement BankAccount Policy/Limitation.
*/
}
}
if some other part of code directly access balanceAmount field and set balance amount to 70000Rs which is not acceptable. Here in this case we can not prevent some other part of code from accessing balanceAmount field.
So what we can do?
=> Answer is we can make balanceAmount field private so that no other code can directly access it and allowing access to that field only via public method which operates on balanceAmount field. Main role of method is that we can write some prevention logic inside method so that field can not be initialized with more than 50000Rs. Here we are making binding between data field called balanceAmount and method which operates on that field. This process is called Encapsulation.(it is all about protecting fields using access modifier such as private)
Encapsulation is one way to achieve abstraction....but How?
=> User of this method will not know about implementation (How amount gets credited? logic and all that stuff) of method which he/she will invoke. Not knowing about implementation details by user is called Abstraction(Hiding details from user).
Following will be the implementation of class:
class BankAccount
{
**private** double balanceAmount;
**public** void UpdateBankBalance(double amount)
{
if(balanceAmount + amount > 50000)
{
Console.WriteLine("Bank balance can not be more than 50000, Transaction can
not be proceed");
}
else
{
balanceAmount = balanceAmount + amount;
Console.WriteLine("Amount has been credited to your bank account
successfully.....");
}
}
}
class AccountHolder
{
BankAccount mybankAccount = new BankAccount();
DoAmountCreditInBankAccount()
{
mybankAccount.UpdateBankBalance(some_amount);
/*
mybankAccount.balanceAmount will not be accessible due to its protection level
directly from AccountHolder so account holder will consume BankAccount public
method UpdateBankBalance(double amount) to update his/her balance.
*/
}
}
Simply put, abstraction is all about making necessary information for interaction with the object visible, while encapsulation enables a developer to implement the desired level of abstraction.
Encapsulation: Hiding the information at the implementation level. This deals with properties or methods which will be hidden from other objects.
Abstraction: Hiding the information at the idea level/design level. Here we decide that something will be abstract(hidden) from the user while thinking of an idea. Abstraction can be achieved using encapsulation at the implementation level.

Difference between abstraction and encapsulation?

What is the precise difference between encapsulation and abstraction?
Most answers here focus on OOP but encapsulation begins much earlier:
Every function is an encapsulation; in pseudocode:
point x = { 1, 4 }
point y = { 23, 42 }
numeric d = distance(x, y)
Here, distance encapsulates the calculation of the (Euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple.
Abstraction is the process of generalisation: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is C’s qsort function to sort data:
The thing about qsort is that it doesn't care about the data it sorts — in fact, it doesn’t know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just C’s way of saying “I don't care about the type of data” (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.
Encapsulation and abstraction go hand in hand so much so that you could make the point that they are truly inseparable. For practical purposes, this is probably true; that said, here’s an encapsulation that’s not much of an abstraction:
class point {
numeric x
numeric y
}
We encapsulate the point’s coordinate, but we don’t materially abstract them away, beyond grouping them logically.
And here’s an example of abstraction that’s not encapsulation:
T pi<T> = 3.1415926535
This is a generic variable pi with a given value (π), and the declaration doesn’t care about the exact type of the variable. Admittedly, I’d be hard-pressed to find something like this in real code: abstraction virtually always uses encapsulation. However, the above does actually exist in C++(14), via variable templates (= generic templates for variables); with a slightly more complex syntax, e.g.:
template <typename T> constexpr T pi = T{3.1415926535};
Many answers and their examples are misleading.
Encapsulation is the packing of "data" and "functions operating on that data" into a single component and restricting the access to some of the object's components.
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object's definition.
Abstraction is a mechanism which represent the essential features without including implementation details.
Encapsulation:-- Information hiding.
Abstraction:-- Implementation hiding.
Example (in C++):
class foo{
private:
int a, b;
public:
foo(int x=0, int y=0): a(x), b(y) {}
int add(){
return a+b;
}
}
Internal representation of any object of foo class is hidden outside of this class. --> Encapsulation.
Any accessible member (data/function) of an object of foo is restricted and can only be accessed by that object only.
foo foo_obj(3, 4);
int sum = foo_obj.add();
Implementation of method add is hidden. --> Abstraction.
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).
Here's a good read: Abstraction, Encapsulation, and Information Hiding by Edward V. Berard of the Object Agency.
encapsulation puts some things in a box and gives you a peephole; this keeps you from mucking with the gears.
abstraction flat-out ignores the details that don't matter, like whether the things have gears, ratchets, flywheels, or nuclear cores; they just "go"
examples of encapsulation:
underpants
toolbox
wallet
handbag
capsule
frozen carbonite
a box, with or without a button on it
a burrito (technically, the tortilla around the burrito)
examples of abstraction:
"groups of things" is an abstraction (which we call aggregation)
"things that contains other things" is an abstraction (which we call composition)
"container" is another kind of "things that contain other things" abstraction; note that all of the encapsulation examples are kinds of containers, but not all containers exhibit/provide encapsulation. A basket, for example, is a container that does not encapsulate its contents.
Encapsulation means-hiding data like using getter and setter etc.
Abstraction means- hiding implementation using abstract class and interfaces etc.
Abstraction is generalized term. i.e. Encapsulation is subset of Abstraction.
Abstraction
Encapsulation
It solves an issue at the design level.
Encapsulation solves an issue at implementation level.
hides the unnecessary detail but shows the essential information.
It hides the code and data into a single entity or unit so that the data can be protected from the outside world.
Focuses on the external lookout.
Focuses on internal working.
Lets focus on what an object does instead of how it does it.
Lets focus on how an object does something.
Example: Outer look of mobile, like it has a display screen and buttons.
Example: Inner details of mobile, how button and display screen connect with each other using circuits.
Example: The solution architect is the person who creates the high-level abstract technical design of the entire solution, and this design is then handed over to the the development team for implementation.
Here, solution architect acts as a abstract and development team acts as a Encapsulation.
Example: Encapsulation(networking) of user data
image courtesy
Abstraction (or modularity) – Types enable programmers to think at a higher level than the bit or byte, not bothering with low-level implementation. For example, programmers can begin to think of a string as a set of character values instead of as a mere array of bytes. Higher still, types enable programmers to think about and express interfaces between two of any-sized subsystems. This enables more levels of localization so that the definitions required for interoperability of the subsystems remain consistent when those two subsystems communicate.
Source
Java example
A lot of good answers are provided above but I am going to present my(Java) viewpoint here.
Data Encapsulation simply means wrapping and controlling access of logically grouped data in a class. It is generally associated with another keyword - Data Hiding. This is achieved in Java using access modifiers.
A simple example would be defining a private variable and giving access to it using getter and setter methods or making a method private as it's only use is withing the class. There is no need for user to know about these methods and variables.
Note : It should not be misunderstood that encapsulation is all about data hiding only. When we say encapsulation, emphasis should be on grouping or packaging or bundling related data and behavior together.
Data Abstraction on the other hand is concept of generalizing so that the underneath complex logic is not exposed to the user. In Java this is achieved by using interfaces and abstract classes.
Example -
Lets say we have an interface Animal and it has a function makeSound(). There are two concrete classes Dog and Cat that implement this interface. These concrete classes have separate implementations of makeSound() function. Now lets say we have a animal(We get this from some external module). All user knows is that the object that it is receiving is some Animal and it is the users responsibility to print the animal sound. One brute force way is to check the object received to identify it's type, then typecast it to that Animal type and then call makeSound() on it. But a neater way is to abstracts thing out. Use Animal as a polymorphic reference and call makeSound() on it. At runtime depending on what the real Object type is proper function will be invoked.
More details here.
Complex logic is in the circuit board which is encapsulated in a touchpad and a nice interface(buttons) is provided to abstract it out to the user.
PS: Above links are to my personal blog.
These are somewhat fuzzy concepts that are not unique to Computer Science and programming. I would like to offer up some additional thoughts that may help others understand these important concepts.
Short Answer
Encapsulation - Hiding and/or restricting access to certain parts of a system, while exposing the necessary interfaces.
Abstraction - Considering something with certain characteristics removed, apart from concrete realities, specific objects, or actual instances, thereby reducing complexity.
The main similarity is that these techniques aim to improve comprehension and utility.
The main difference is that abstraction is a means of representing things more simply (often to make the representation more widely applicable), whereas encapsulation is a method of changing the way other things interact with something.
Long Answer
Encapsulation
Here's an example of encapsulation that hopefully makes things more clear:
Here we have an Arduino Uno, and an Arduino Uno within an enclosure. An enclosure is a great representation of what encapsulation is all about.
Encapsulation aims to protect certain components from outside influences and knowledge as well as expose components which other things should interface with. In programming terms, this involves information hiding though access modifiers, which change the extent to which certain variables and/or properties can be read and written.
But beyond that, encapsulation also aims to provide those external interfaces much more effectively. With our Arduino example, this could include the nice buttons and screen which makes the user's interaction with the device much simpler. They provide the user with simple ways to affect the device's behavior and gain useful information about its operation which would otherwise be much more difficult.
In programming, this involves the grouping of various components into a separable construct, such as a function, class, or object. It also includes providing the means of interacting with those constructs, as well as methods for gaining useful information about them.
Encapsulation helps programmers in many many additional ways, not least of which is improved code maintainability and testability.
Abstraction
Although many other answers here defined abstraction as generalization, I personally think that definition is misguided. I would say that generalization is actually a specific type of abstraction, not the other way around. In other words, all generalizations are abstractions, but all abstractions are not necessarily generalizations.
Here's how I like to think of abstraction:
Would you say the image there is a tree? Chances are you would. But is it really a tree? Well, of course not! It's a bunch of pixels made to look like something we might call a tree. We could say that it represents an abstraction of a real tree. Notice that several visual details of the tree are omitted. Also, it does not grow, consume water, or produce oxygen. How could it? it's just a bunch of colors on a screen, represented by bytes in your computer memory.
And here is the essence of abstraction. It's a way of simplifying things so they are easier to understand. Every idea going through your head is an abstraction of reality. Your mental image of a tree is no more an actual tree than this jpeg is.
In programming, we might use this to our advantage by creating a Tree class with methods for simulated growing, water consuming, and oxygen production. Our creation would be something that represents our experience of actual trees, and only includes those elements that we really care about for our particular simulation. We use abstraction as a way of representing our experience of something with bytes and mathematics.
Abstract Classes
Abstraction in programming also allows us to consider commonalities between several "concrete" object types (types that actually exist) and define those commonalities within a unique entity. For example, our Tree class may inherit from an abstract class Plant, which has several properties and methods which are applicable to all of our plant-like classes, but removes those that are specific to each type of plant. This can significantly reduce duplication of code, and improves maintainability.
The practical difference of an abstract class and plain class is that conceptually there's no "real" instances of the abstract class. It wouldn't make sense to construct a Plant object because that's not specific enough. Every "real" Plant is also a more specific type of Plant.
Also, if we want our program to be more realistic, we might want to consider the fact that our Tree class might be too abstract itself. In reality, every Tree is a more specific type of Tree, so we could create classes for those types such as Birch, Maple, etc. which inherit from our, perhaps now abstract, Tree class.
JVM
Another good example of abstraction is the Java Virtual Machine (JVM), which provides a virtual or abstract computer for Java code to run on. It essentially takes away all of the platform specific components of a system, and provides an abstract interface of "computer" without regard to any system in particular.
The Difference
Encapsulation differs from abstraction in that it doesn't have anything to do with how 'real' or 'accurate' something is. It doesn't remove components of something to make it simpler or more widely applicable. Rather it may hide certain components to achieve a similar purpose.
Abstraction lets you focus on what the object does instead of how it does it
Encapsulation means hiding the internal details or mechanics of how an object does something.
Like when you drive a car, you know what the gas pedal does but you may not know the process behind it because it is encapsulated.
Let me give an example in C#. Suppose you have an integer:
int Number = 5;
string aStrNumber = Number.ToString();
you can use a method like Number.ToString() which returns you characters representation of the number 5, and stores that in a string object. The method tells you what it does instead of how it does it.
Encapsulation: Is hiding unwanted/un-expected/propriety implementation details from the actual users of object.
e.g.
List<string> list = new List<string>();
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**
Difference Between Abstraction and Encapsulation.
Abstraction: The idea of presenting something in a simplified / different way, which is either easier to understand and use or more pertinent to the situation.
Consider a class that sends an email... it uses abstraction to show itself to you as some kind of messenger boy, so you can call emailSender.send(mail, recipient). What it actually does - chooses POP3 / SMTP, calling servers, MIME translation, etc, is abstracted away. You only see your messenger boy.
Encapsulation: The idea of securing and hiding data and methods that are private to an object. It deals more with making something independent and foolproof.
Take me, for instance. I encapsulate my heart rate from the rest of the world. Because I don't want anyone else changing that variable, and I don't need anyone else to set it in order for me to function. Its vitally important to me, but you don't need to know what it is, and you probably don't care anyway.
Look around you'll find that almost everything you touch is an example of both abstraction and encapsulation. Your phone, for instance presents to you the abstraction of being able to take what you say and say it to someone else - covering up GSM, processor architecture, radio frequencies, and a million other things you don't understand or care to. It also encapsulates certain data from you, like serial numbers, ID numbers, frequencies, etc.
It all makes the world a nicer place to live in :D
Abstraction: Only necessary information is shown. Let's focus on the example of switching on a computer. The user does not have to know what goes on while the system is still loading (that information is hidden from the user).
Let's take another example, that of the ATM. The customer does not need to know how the machine reads the PIN and processes the transaction, all he needs to do is enter the PIN, take the cash and leave.
Encapsulation: Deals with hiding the sensitive data of a clas hence privatising part of it. It is a way of keeping some information private to its clients by allowing no access to it from outside.
Another example:
Suppose I created an immutable Rectangle class like this:
class Rectangle {
public:
Rectangle(int width, int height) : width_(width), height_(height) {}
int width() const { return width_; }
int height() const { return height_; }
private:
int width_;
int height_;
}
Now it's obvious that I've encapsulated width and height (access is somehow restricted), but I've not abstracted anything (okay, maybe I've ignored where the rectangle is located in the coordinates space, but this is a flaw of the example).
Good abstraction usually implies good encapsulation.
An example of good abstraction is a generic database connection class. Its public interface is database-agnostic, and is very simple, yet allows me to do what I want with the connection. And you see? There's also encapsulation there, because the class must have all the low-level handles and calls inside.
A mechanism that prevents the data of a particular objects safe from intentional or accidental misuse by external functions is called "data Encapsulation"
The act of representing essential features without including the background details or explanations is known as abstraction
Abstraction and Encapsulation by using a single generalized example
------------------------------------------------------------------------------------------------------------------------------------
We all use calculator for calculation of complex problems !
Abstraction : Abstraction means to show What part of functionality.
Encapsulation : Encapsulation means to hide the How part of the functionality.
Lets take a very simple example
/// <summary>
/// We have an Employee class having two properties EmployeeName and EmployeeCode
/// </summary>
public class Employee
{
public string EmplpyeeName { get; set; }
public string EmployeeCode { get; set; }
// Add new employee to DB is the main functionality, so are making it public so that we can expose it to external environment
// This is ABSTRACTION
public void AddEmployee(Employee obj)
{
// "Creation of DB connection" and "To check if employee exists" are internal details which we have hide from external environment
// You can see that these methods are private, external environment just need "What" part only
CreateDBConnection();
CheckIfEmployeeExists();
}
// ENCAPLUSATION using private keyword
private bool CheckIfEmployeeExists()
{
// Here we can validate if the employee already exists
return true;
}
// ENCAPLUSATION using private keyword
private void CreateDBConnection()
{
// Create DB connection code
}
}
Program class of Console Application
class Program
{
static void Main(string[] args)
{
Employee obj = new Employee();
obj.EmplpyeeName = "001";
obj.EmployeeCode = "Raj";
// We have exposed only what part of the functionality
obj.AddEmployee(obj);
}
}
Let's take the example of a stack. It could be implemented using an array or a linked list. But the operations it supports are push and pop.
Now abstraction is exposing only the interfaces push and pop. The underlying representation is hidden (is it an array or a linked list?) and a well-defined interface is provided. Now how do you ensure that no accidental access is made to the abstracted data? That is where encapsulation comes in. For example, classes in C++ use the access specifiers which ensure that accidental access and modification is prevented. And also, by making the above-mentioned interfaces as public, it ensures that the only way to manipulate the stack is through the well-defined interface. In the process, it has coupled the data and the code that can manipulate it (let's not get the friend functions involved here). That is, the code and data are bonded together or tied or encapsulated.
Encapsulation is wrapping up complexity in one capsule that is class & hence Encapsulation…
While abstraction is the characteristics of an object which differentiates from other object...
Abstraction can be achieved by making class abstract having one or more methods abstract. Which is nothing but the 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 achieved keeping data and the behaviour in one capsule that is class & by making use of access modifiers like public, private, protected along with inheritance, aggregation or composition. So you only show only required things, that too, only to the extent you want to show. i.e. public, protected, friendly & private ka funda……
e.g. GM decides to use the abstracted design of car above. But they have various products having the same characteristics & doing almost same functionality. So they write a class which extends the above abstract class. It says how gear box should work, how break should work, how steering wheel should work. Then all the products just use this common functionality. They need not know how the gear box works or break works or steering wheal works. Indivisual product can surely have more features like a/c or auto lock etc…..
Both are powerful; but using abstraction require more skills than encapsulation and bigger applications/products can not survive with out abstraction.
I will try to demonstrate Encapsulation in a simple way.. Lets see..
The wrapping up of data and functions into a single unit (called
class) is known as encapsulation. Encapsulation containing and hiding
information about an object, such as internal data structures and
code.
Encapsulation is -
Hiding Complexity,
Binding Data and Function together,
Making Complicated Method's Private,
Making Instance Variable's Private,
Hiding Unnecessary Data and Functions from End User.
Encapsulation implements Abstraction.
And Abstraction is -
Showing Whats Necessary,
Data needs to abstract from End User,
Lets see an example-
The below Image shows a GUI of "Customer Details to be ADD-ed into a Database".
By looking at the Image we can say that we need a Customer Class.
Step - 1: What does my Customer Class needs?
i.e.
2 variables to store Customer Code and Customer Name.
1 Function to Add the Customer Code and Customer Name into Database.
namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
//my DB code will go here
}
Now only ADD method wont work here alone.
Step -2: How will the validation work, ADD Function act?
We will need Database Connection code and Validation Code (Extra Methods).
public bool Validate()
{
//Granular Customer Code and Name
return true;
}
public bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.Validate();
obj.CreateDBObject();
obj.ADD();
}
}
Now there is no need of showing the Extra Methods(Validate(); CreateDBObject() [Complicated and Extra method] ) to the End User.End user only needs to see and know about Customer Code, Customer Name and ADD button which will ADD the record.. End User doesn't care about HOW it will ADD the Data to Database?.
Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction.
So making those Complicated and Extra method as Private instead Public(i.e Hiding those methods) and deleting the obj.Validate(); obj.CreateDBObject(); from main in class Program we achieve Encapsulation.
In other words Simplifying Interface to End User is Encapsulation.
So now the code looks like as below -
namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
//my DB code will go here
}
private bool Validate()
{
//Granular Customer Code and Name
return true;
}
private bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.ADD();
}
}
Summary :
Step -1: What does my Customer Class needs? is Abstraction.
Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.
P.S. - The code above is hard and fast.
Abstraction--- Hiding Implementation--at Design---Using Interface/Abstract calsses
Encapsulation--Hiding Data --At Development---Using access modifiers(public/private)
From this
Difference between Encapsulation and Abstraction in OOPS
Abstraction and Encapsulation are two important Object Oriented Programming (OOPS) concepts. Encapsulation and Abstraction both are interrelated terms.
Real Life Difference Between Encapsulation and Abstraction
Encapsulate means to hide. Encapsulation is also called data hiding.You can think Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation.
Abstraction refers to showing only the necessary details to the intended user. As the name suggests, abstraction is the "abstract form of anything". We use abstraction in programming languages to make abstract class. Abstract class represents abstract view of methods and properties of class.
Implementation Difference Between Encapsulation and Abstraction
Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier.
OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make sure data is used in an appropriate manner) by preventing programmers from accessing data in a non-intended manner. Through encapsulation, only a predetermined group of functions can access the data. The collective term for datatypes and operations (methods) bundled together with access restrictions (public/private, etc.) is a class.
The below paragraph helped me to understand how they differ from each other:
Data encapsulation is a mechanism of bundling the data, and the
functions that use them and data abstraction is a mechanism of
exposing only the interfaces and hiding the implementation details
from the user.
You can read more here.
Information hiding is not strictly required for abstraction or encapsulation. Information might be ignored, but does not have to be hidden.
Encapsulation is the ability to treat something as a single thing, even though it may be composed of many complex parts or ideas. For example, I can say that I'm sitting in a "chair" rather than referring to the many various parts of that chair each with a specific design and function, all fitting together precisely for the purpose of comfortably holding my butt a few feet away from the floor.
Abstraction is enabled by encapsulation. Because we encapsulate objects, we can think about them as things which relate to each other in some way rather than getting bogged down in the subtle details of internal object structure. Abstraction is the ability to consider the bigger picture, removed from concern over little details. The root of the word is abstract as in the summary that appears at the top of a scholarly paper, not abstract as in a class which can only be instantiated as a derived subclass.
I can honestly say that when I plop my butt down in my chair, I never think about how the structure of that chair will catch and hold my weight. It's a decent enough chair that I don't have to worry about those details. So I can turn my attention toward my computer. And again, I don't think about the component parts of my computer. I'm just looking at a part of a webpage that represents a text area that I can type in, and I'm communicating in words, barely even thinking about how my fingers always find the right letters so quickly on the keyboard, and how the connection is ultimately made between tapping these keys and posting to this forum. This is the great power of abstraction. Because the lower levels of the system can be trusted to work with consistency and precision, we have attention to spare for greater work.
The more I read, more I got confused. So, simply here is what I understood:
Encapsulation:
We generally see a watch from outside and it's components are encapsulated inside it's body. We have some kind of control for different operations. This way of hiding details and exposing control (e.g. setting time) is encapsulation.
Abstraction:
So far we were talking about a watch. But we didn't specify what kind of watch. It could be digital or analog, for hand or wall. There are many possibilities. What we do know is, it is a watch and it tells time and that is the only thing we are interested in, the time. This way of hiding details and exposing generic feature or use case is abstraction.
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**
abstraction is hiding non useful data from users
and encapsulation is bind together data into a capsule (a class).
I think encapsulation is way that we achieve abstraction.
The process of Abstraction and Encapsulation both generate interfaces.
An interface generated via encapsulation hides implementation details.
An interface generated via abstraction becomes applicable to more data types, compared to before abstraction.
Abstraction is a contract for the implementation we are going to do. Implementation may get changed over period of time. The various implementations themselves may or may not be hidden but are Masked behind the Abstraction.
Suppose we define all the APIs of a class in an interface then ask the users of our code to depened upon the defined APIs of the interface. We are free to improve or modify the implementation only we must follow the set contract. The users are not coupled with our implementation.
We EXPOSE all the NECESSARY Rules (methods) in abstraction, the implementation of the rules are left for the implementor entities, also the implemention is not part of the abstraction. Its just the signature and declaration what makes the abstraction.
Encapsulation is simply HIDING the internal details by reducing the acess of the states and behaviors. An encapsulated class may or may not have well defined Abstraction.
java.util.List is an abstraction for java.util.ArrayList. The internal states of java.util.ArrayList being marked with non public access modifiers is encapsulation.
Edit
Suppose a class Container.nava implements IContainer , IContainer may declare methods like addElement, removeElements, contains, etc. Here IContainer represents the abstraction for its implementing class. Abstraction is declaring the APIs of the class or a module or a system to the outer world. These APIs become the contract.
That system may be or may not be developed yet. The users of the system now can depend on the declared APIs and are sure any system implementing such a contract will always adhere to the APIs declared, they will always provide tge implementation for those APIs. Once we are writing some concrete entity then deciding to hide our internal states is encapsulation
I Think Encapsulation is a way to implement abstraction. Have a look at the following link.
Abstraction and Encapsulation

How do you explain OO to new programmers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
My relative is studying programming and has a hard time understanding classes. He has trouble understanding for example that you need to instantiate it, that methods cannot access variables in other methods and if you change a variable in one instance of a class it doesn't change for other instances.
I've tried to use analogies like a class definition is like a blueprint of a house. And instances are houses made from that blueprint.
How do you explain classes and OO in general?
Seriously use Animals, it works great. And that's what nailed the concept for me years ago. Just found this C# code. It seems good
// Assembly: Common Classes
// Namespace: CommonClasses
public interface IAnimal
{
string Name
{
get;
}
string Talk();
}
// Assembly: Animals
// Namespace: Animals
public class AnimalBase
{
private string _name;
AnimalBase(string name)
{
_name = name;
}
public string Name
{
get
{
return _name;
}
}
}
// Assembly: Animals
// Namespace: Animals
public class Cat : AnimalBase, IAnimal
{
public Cat(String name) :
base(name)
{
}
public string Talk() {
return "Meowww!";
}
}
// Assembly: Animals
// Namespace: Animals
public class Dog : AnimalBase, IAnimal
{
public Dog(string name) :
base(name)
{
}
public string Talk() {
return "Arf! Arf!";
}
}
// Assembly: Program
// Namespace: Program
// References and Uses Assemblies: Common Classes, Animals
public class TestAnimals
{
// prints the following:
//
// Missy: Meowww!
// Mr. Bojangles: Meowww!
// Lassie: Arf! Arf!
//
public static void Main(String[] args)
{
List<IAnimal> animals = new List<IAnimal>();
animals.Add(new Cat("Missy"));
animals.Add(new Cat("Mr. Bojangles"));
animals.Add(new Dog("Lassie"));
foreach(IAnimal animal in animals)
{
Console.WriteLine(animal.Name + ": " + animal.Talk());
}
}
}
And once he's got this nailed, you challenge him to define Bird (fly), and then Penguin (fly!?)
The best way I got it through to my wife (a chartered accountant) is as follows.
In 'regular' programming you have data (things that are manipulated) and code (things that manipulate) and they're separate. Sometimes you get mixed up because a certain piece of code tries to manipulate the wrong thing.
In my wife's case, I said a invoice arrived (which involves no physical money changing hands) and accidentally updated a bank balance, something she immediately saw as potential fraud (she used to do forensic accounting, everything is potential fraud to her, including most of my share trades :-).
You could just as easily say that a piece of code meant to wash a floor with a huge mop decided to do it with your toothbrush.
With OO programming, the manipulators and manipulatees are inextricably entwined. You don't apply the floor washing process to the floor, instead you command the floor to wash itself. It knows how to do this because the code is part of the object, not something external to it.
In the accounting case above, I think we ended up having the chart of accounts as the object and we told it to apply a invoice to itself. Since it understood the process, it knew which accounts were allowed to be updated (creditors liability account and an expense account if I remember correctly).
Anyway, that's irrelevant and I'm just meandering now. What I'm saying is to express it in terms your target audience will understand. I suppose that's the secret of most teaching.
Like all old farts, I'd like to answer this with a story from my own life.
I started programming basic on a VIC-20. Not knowing anything else, I though this was how all computers were programmed. I thought it was a bit hard to keep track of which variable names I had used and which were still free, (scope problem). I also thought it was hard to divide my program into repeatable chunks using gosub-return and setting and reading the variables that these would use, (lack of methods).
Then I got into Turbo C over MS-DOS. Now I could create my own methods and functions! I was no longer stuck with the old finite set of commands in basic. I felt like I was creating a new language for every program I wrote. C gave me more expressive power.
C++ was the first object oriented language I heard about. The big moment for me was when I understood that I could create my own data types, and even overload the operators. Again, it felt like I could create my own language containing both new functions and data types, complete with operators.
That's how I would sell OO to a new programmer. Explain that it gives expressive power because they can define their own data types. I always thought encapsulation was a better selling point than inheritance.
I assume the target knows how to use graphical user interfaces. I found the best way is to describe OOP with stuff that they are really used for. Say
Class
A Window is a class. It has methods like
Show a window
Enable a window
Set the window's title
A Window has attributes. That is data associated with it. It is encapsulated into the class, together with the functions that operate on them
A Window has dimensions. Width and height.
A Window has possibly a parent window, and possibly children.
A Window has a title
Object
There are many windows. Each particular window is an object of the class Window. A Parent window containing 10 windows makes 11 Window objects.
Deriveration
A Button is a Window. It has dimensions has a parent window and has a title, the label of a button. It's a special kind of a window. When you ask for a window object, someone can give you a Button. A Button can add functions and data that are specific for a button:
A Button has a state. It can be in a pressed state, and unpressed state.
A Button can be the default button in a Window.
While you are explaining OO with animals, do not forget to illustrate the "is-a" relationship with Stinger missiles-armed kangaroos ;-)
The kangaroos scattered, as predicted, and the Americans nodded appreciatively . . . and then did a double-take as the kangaroos reappeared from behind a hill and launched a barrage of stinger missiles at the hapless helicopter. (Apparently the programmers had forgotten the remove "that" part of the infantry coding).
The lesson? Objects are defined with certain attributes, and any new object defined in terms of the old one inherits all the attributes. The embarrassed programmers had learned to be careful when reusing object-oriented code, and the Yanks left with the utmost respect for the Australian wildlife.
Read the Java tutorials for some good ideas and real world examples.
How about "each molding is built using a mold", or "each model is built using a template", and so "each object is built using a class" ?
Note that it works for class-oriented OOP (which is what you want), but not for prototype-oriented OOP.
As for explaining OOP to a programmer, I'd add examples illustrating:
Separating state from behavior
Most of the time, an instance describe a state, and a class describe a behavior.
Delegation
An instance delegates its behavior to its class, and the class in turn can delegate its behavior to its superclasses (or mixins or traits)
Polymorphism
If class A inherits from class B, an instance of A can be used anywhere an instance of class B can be used.
Messages & methods
A message (or generic function, or virtual function) is like a question. Most of the time, several classes can answer to this question.
A corresponding method is a possible answer to the question, that resides in a class.
When sending a message to an instance, the instance looks up for a corresponding method in its class. If found, it calls it (with the instance bound to 'self' or 'this'. Otherwise, it looks for a corresponding method in its mixins, traits, or superclasses, and calls it.
If they're old enough to have ever filled out a tax form, show them a 1040EZ and explain that an instance of a class is like a filled-out form: each blank is a member variable of the object, and the form also includes instructions for what to do with the member variables, and those instructions are the member functions of the object. A class itself is like a master copy of the form, from which you can print off an endless number of blank forms to fill out.
One thing that I would counsel to AVOID in trying to communicate the concepts of OO to new programmers is using only examples where objects (in the OO sense) represent real-world physical objects. This will actually make students more confused when they encounter objects used to represent non-physical objects (such as a color scheme, or most of the behavioral patterns in "Design Patterns") or objects used just as a useful way to store related functions and related data in the same place (think Java's java.lang.Math for an example.)
Believe it or not, sports!
I've had success in teaching and mentoring by talking about the way that e.g. a play for a football team is described in terms of how the various positions (Center, Quarterback, Runningback, etc.) interact to accomplish a particular goal. In one version, the positions correspond to classes, and specific persons (Tony Romo, Johnny Unitas, etc.) are instances of the class -- individuals who exhibit the same behaviors as defined by the positions.
The second version of this metaphor is to explain that the positions may be interfaces (in the Java sense) rather than classes. An interface really represents a role fulfilled by any object that implements the methods of the interface. And it's perfectly reasonable for an object (via its class, in Java) to implement multiple interfaces, just as it is possible for a talented individual to play more than one position on a sports team.
Finally, the play is like a pattern, in that it describes how a set of roles interact to accomplish some specific goal.
An object is a black box, which you can't see through. Public methods are buttons on them. Protected methods are buttons hidden on the bottom, private methods are dip switches inside.
Let's see a washer as an object. We don't know how it works. We don't care if it's powered by natural gas, diesel, electricity, or plutonium. However, the mechanism and internal structure will vary greatly depending on the energy source like a combustion engine is needed for some. We don't care as long as if we push a "Wash" button, it washes our clothes.
Let's turn the washer not Object-oriented. Expose all the buttons by arranging them on the top. Customers can now turbo-charge the engine by tweaking some dip switches. Make the chassis transparent. Now, you can see your energy-saving washing machine is actually hybrid-powered. There are some monkeys in it. You free them into the wild, and the machine eats up your utility bill like a gas-guzzler.
Object-oriented programming is one technique of raising the level of abstraction by means of which the programmer communicates with the computer: from the level of flipping individual bits on and off, from the level of punching holes in paper cards, from the level of extraordinarily complex sequences of basic instruction codes, from the level of less complicated definitions of reusable templates for blocks of data and reusable blocks of code (structs and procedures), to the level of transcribing the concepts in the programmer's mind into code, so that what goes on inside the computer comes to resemble, for the programmer, what goes on outside the computer in the world of physical objects, intangible assets, and cause-and-effect.
the best book i've ever on object-oriented programming is Betrand's "Object-Oriented Software Construction" - if you really want to get the basics, there is no way around it.
I explain that procedural program is built around the "verbs" of the system, the things you want the system to do, whereas object-oriented programming is build about the "nouns," the things in the system, and what they are capable of, and that for many people this allows for a more straightforward mapping from the problem domain to software.
For the example, I use cars -- "Honda Accord" is a class, whereas the vehicle sitting in the parking lot is an object, an instance of a Honda Accord. A Honda Accord is a sedan, which is a car, which is an automobile, which is a motorized vehicle, which is a mode of transportation, etc. I cannot do anything with a car until I have a physical car to work with -- it doesn't help me that the idea of a Honda Accord exists.
It also helps for discussing interfaces and polymorphism -- the gas pedal means accelerate, regardless what the car does behind the scenes to make that happen. There are "private" parts of the car that I as user do not have access to -- I cannot directly apply an individual brake.
Since the issue is to explain to a new programmer and not to a mother or a wife, I would go right straight to the point. OO is about three main concepts:
Inheritance: a dog is an animal, parent-child, is-a relationship test, etc.
Encapsulation: public-private (protected), information hiding, internal underlying details are not important to the users of the class, protect users from future changes in the implementation.
Polymorphism: run-time binding, late binding, method that gets invoked depends on the type of the object and not the reference or pointer to the object.
Also, depending on how much the new programmer has been doing a procedural language, I would need to help him/her unlearn that the functions or procedures are no longer central.
Games are good.
There are gameobjects, from this walls, enemies and players inherit.
The gameobjects should be renderable have collision-logic etc. The enemies have ai-logic while the player is keyboard controlled.
Some UI-elements are also good, there are buttons, inputboxes etc that all inherit from some baseobject that has code for managing mouse-events etc.
I don't like the animal-example because i've never seen a "real" program that has ever had to use of animals in that way. It will only make people use inheritance all over the place and you will end up with cubes inheriting from rectangles that inherit from lines (why does so many books insist on using this as example? ).
OOP is a higher level of abstraction, a programmer can't really come to grasp it unless he has a good understanding of the normal (read: procedural) way of programming, and he must be able to write some programs that do something useful.
For me it took a series of several lectures by one of my university profs, where he discussed many theoretical aspects of programming, he tried to convince us that programming is about manipulating data, and that this data is a representation of the "state(s)" of the program, and some other abstract stuff that I forgot now! But the point is, it's hard to understand OOP without some theoretical abstract discussion first, and this discussion wouldn't make any sense to a person who hadn't had experience writing some real code.
After the theoretical discussion, you give an example of a moderately complex program, written in procedural style, and slowly convert it, step by step, into object oriented style. After the concrete example, you should go back to the theoretical discussion and just summarize the main points, directly relate the theoretical constructs to the concrete example, e.g you can talk about how the name, age, and salary of an employee represent his state.

What are the different types of encapsulation?

What are the different types of encapsulation?
Am I right in thinking this basically refers to central OO concepts such as Abstraction, Polymorphism and Inheritance?
My understanding of encapsulation is that it is a method of hiding data / functionality, but I never really considered Polymorphism or Inheritance a form of encapsulation, although I can see how polymorphism could be considered encapsulation as it can hide the exact type of the object you are interacting with.
So, would you say that's about it, or am I missing some core concepts?
edit I just noticed in the comments someone mentioned it could refer to private / public methods, perhaps I'm thinking in to the question too much and expecting a more complicated answer than it really is?
You're thinking too much I think.
http://en.wikipedia.org/wiki/Information_hiding
Excerpt from this article:
Information hiding in computer science is the principle of hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed. The protection involves providing a stable interface which shields the remainder of the program from the implementation (the details that are most likely to change).
One common form of encapsulation is using properties to hide private data fields. An even more common form is the use of OO to encapsulate the complexity of software into well divisoned classes with roles and responsibilities. This is a key tennant of OO, as it moves from a monolithic procedural design style to a more structured style which strives to hide all irrelevant information except that which pertains to the particular task your working on.
It is my view and understanding that the term encapsulation (to encapsulate) is the art/science of capturing the essence of something for the purpose of display. In fact, by definition - to encapsulate is to package something or enclose it in another container. Therefore the term encapsulation would mean to take the essence of what you are attempting to achieve and packaging it in a useful form so that it can be reused as necessary.
So to interpret this, it would mean to package material in a form that would make it more useful later.
So really...interpret this as you see fit. I see it as taking a bunch of algorithms and utilities and creating a class structure that can be used as an API in other projects. This encapsulated code could be inherited and/or extended to make it useful for modified purposes without changing the underlying essence of the API.
Therefore, abstraction, polymorphism and inheritance aren't forms of encapsulation, but forms of extending and modifying encapsulated code.
Different forms of encapsulation would mean the modifiers on properties, methods, fields and classes - that is public, private, static, virtual (in C#). Everything else (i.e. overloads, overrides, shadows) is a modification or an extension to that encapsulation.
You may consider the modified code an encapsulation which could then be further inherited/abstracted/extended, but the package which is to be extended is the encapsulated product.
Encapsulation is defined by the International Organisation for Standardization's International Standard: "Information technology – Open Distributed Processing," ISO/IEC 10746, 1998.
It's defined in terms of more primitive definitions:
Entity: Any concrete or abstract thing of interest.
Object: A model of an entity. An object is characterised by its behaviour and,
dually, by its state.
Behaviour (of an object): A collection of actions with a set of constraints on
when they may occur.
Interface: An abstraction of the behaviour of an object that consists of a
subset of the interactions of that object together with a set of constraints
on when they may occur.
Encapsulation: the property that the information contained in an object is
accessible only through interactions at the interfaces supported by the
object.
The ISO does not define different types of encapsulation.
Other posts have mentioned information hiding. The ISO does not define encapsulation explicitly in terms of information hiding, though it does seem implicit, see "Encapsulation theory fundamentals," at http://www.edmundkirwan.com/pub/
Ed.
Encapsulation is more than simply information hiding. That is one aspect of it. It has to do with the interface to a module. An interface provides two very important functions: encapsulation and abstraction.
Abstraction is when a client of a module does not need to know more than what is in the interface.
and
Encapsulation is when a client of a module isn't able to know more than what is in the interface.
(Both definitions from Using UML by Perdita Stevens)
Since encapsulation simply refers to "information hiding" then I would imagine that a lot of things can be categorized as encapsulation. However I tend to think of encapsulation as "implementation hiding", in other words it is a tool that I use to create loose coupling between anything I write and anything client of what I have written.
So I tend to believe, pragmatically, that encapsulation is any paradigm or best-practice that allows me to present a clean, solid interface to any client.
Generally the usage of the word is pretty close to what it says. You encapsulate something when you contain it, and don't let any of the deals loose. The best way to think about it is that you are taking something and putting it into a black-box where no one can see the details anymore. The box hides everything, providing some other disassociated interface in its place.
Information hiding is just one aspect of encapsulation, since along with the data you can also hide any of the details of the code itself. The purpose of encapsulating a part of your system is to draw that bit of complexity away from the whole, thus making it easier to understand the separate details (on both sides). More?
Paul.
"Candidate Definitions for Encapsulation:
Physically grouping together related operations or things.
GateKeeper of state or data.
Hiding implementation."
Sourced from: Encapsulation Definition
There are two parts/ways to achieve Encapsulation:
First, encapsulation is a technique that packages related data and behaviors into a single unit, i.e, Physical grouping of operations(behaviors)
E.g.:-
class Person {
String name;
int age;
void talk() {
}
void think() {
}
void work() {
}
void play() {
}
}
Second, encapsulation is a technique for protecting data from misuse by the outside world, which is referred as ‘information hiding’ or ‘data hiding’.
E.g.:-
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
Sourced from: What is Encapsulation in Java - the WHAT, WHY and HOW, spoiler author cites Interface as an example, which is not true. Interface are for Abstraction

Why would I want to use Interfaces? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.
One specific example: interfaces are a good way of specifying a contract that other people's code must meet.
If I'm writing a library of code, I may write code that is valid for objects that have a certain set of behaviours. The best solution is to specify those behaviours in an interface (no implementation, just a description) and then use references to objects implementing that interface in my library code.
Then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! :-)
Another specific example: two teams working on different components that must co-operate. If the two teams sit down on day 1 and agree on a set of interfaces, then they can go their separate ways and implement their components around those interfaces. Team A can build test harnesses that simulate the component from Team B for testing, and vice versa. Parallel development, and fewer bugs.
The key point is that interfaces provide a layer of abstraction so that you can write code that is ignorant of unnecessary details.
The canonical example used in most textbooks is that of sorting routines. You can sort any class of objects so long as you have a way of comparing any two of the objects. You can make any class sortable therefore by implementing the IComparable interface, which forces you to implement a method for comparing two instances. All of the sort routines are written to handle references to IComparable objects, so as soon as you implement IComparable you can use any of those sort routines on collections of objects of your class.
The easiest way of understanding interfaces is that they allow different objects to expose COMMON functionality. This allows the programmer to write much simplier, shorter code that programs to an interface, then as long as the objects implement that interface it will work.
Example 1:
There are many different database providers, MySQL, MSSQL, Oracle, etc. However all database objects can DO the same things so you will find many interfaces for database objects. If an object implements IDBConnection then it exposes the methods Open() and Close(). So if I want my program to be database provider agnostic, I program to the interface and not to the specific providers.
IDbConnection connection = GetDatabaseConnectionFromConfig()
connection.Open()
// do stuff
connection.Close()
See by programming to an interface (IDbconnection) I can now SWAP out any data provider in my config but my code stays the exact same. This flexibility can be extremely useful and easy to maintain. The downside to this is that I can only perform 'generic' database operations and may not fully utilize the strength that each particular provider offers so as with everything in programming you have a trade off and you must determine which scenario will benefit you the most.
Example 2:
If you notice almost all collections implement this interface called IEnumerable. IEnumerable returns an IEnumerator which has MoveNext(), Current, and Reset(). This allows C# to easily move through your collection. The reason it can do this is since it exposes the IEnumerable interface it KNOWS that the object exposes the methods it needs to go through it. This does two things. 1) foreach loops will now know how to enumerate the collection and 2) you can now apply powerful LINQ exprssions to your collection. Again the reason why interfaces are so useful here is because all collections have something in COMMON, they can be moved through. Each collection may be moved through a different way (linked list vs array) but that is the beauty of interfaces is that the implementation is hidden and irrelevant to the consumer of the interface. MoveNext() gives you the next item in the collection, it doesn't matter HOW it does it. Pretty nice, huh?
Example 3:
When you are designing your own interfaces you just have to ask yourself one question. What do these things have in common? Once you find all the things that the objects share, you abstract those properties/methods into an interface so that each object can inherit from it. Then you can program against several objects using one interface.
And of course I have to give my favorite C++ polymorphic example, the animals example. All animals share certain characteristics. Lets say they can Move, Speak, and they all have a Name. Since I just identified what all my animals have in common and I can abstract those qualities into the IAnimal interface. Then I create a Bear object, an Owl object, and a Snake object all implementing this interface. The reason why you can store different objects together that implement the same interface is because interfaces represent an IS-A replationship. A bear IS-A animal, an owl IS-A animal, so it makes since that I can collect them all as Animals.
var animals = new IAnimal[] = {new Bear(), new Owl(), new Snake()} // here I can collect different objects in a single collection because they inherit from the same interface
foreach (IAnimal animal in animals)
{
Console.WriteLine(animal.Name)
animal.Speak() // a bear growls, a owl hoots, and a snake hisses
animal.Move() // bear runs, owl flys, snake slithers
}
You can see that even though these animals perform each action in a different way, I can program against them all in one unified model and this is just one of the many benefits of Interfaces.
So again the most important thing with interfaces is what do objects have in common so that you can program against DIFFERENT objects in the SAME way. Saves time, creates more flexible applications, hides complexity/implementation, models real-world objects / situations, among many other benefits.
Hope this helps.
One typical example is a plugin architecture. Developer A writes the main app, and wants to make certain that all plugins written by developer B, C and D conform to what his app expects of them.
Interfaces define contracts, and that's the key word.
You use an interface when you need to define a contract in your program but you don't really care about the rest of the properties of the class that fulfills that contract as long as it does.
So, let's see an example. Suppose you have a method which provides the functionality to sort a list. First thing .. what's a list? Do you really care what elements does it holds in order to sort the list? Your answer should be no... In .NET (for example) you have an interface called IList which defines the operations that a list MUST support so you don't care the actual details underneath the surface.
Back to the example, you don't really know the class of the objects in the list... neither you care. If you can just compare the object you might as well sort them. So you declare a contract:
interface IComparable
{
// Return -1 if this is less than CompareWith
// Return 0 if object are equal
// Return 1 if CompareWith is less than this
int Compare(object CompareWith);
}
that contract specify that a method which accepts an object and returns an int must be implemented in order to be comparable. Now you have defined an contract and for now on you don't care about the object itself but about the contract so you can just do:
IComparable comp1 = list.GetItem(i) as IComparable;
if (comp1.Compare(list.GetItem(i+1)) < 0)
swapItem(list,i, i+1)
PS: I know the examples are a bit naive but they are examples ...
When you need different classes to share same methods you use Interfaces.
Interfaces are absolutely necessary in an object-oriented system that expects to make good use of polymorphism.
A classic example might be IVehicle, which has a Move() method. You could have classes Car, Bike and Tank, which implement IVehicle. They can all Move(), and you could write code that didn't care what kind of vehicle it was dealing with, just so it can Move().
void MoveAVehicle(IVehicle vehicle)
{
vehicle.Move();
}
The pedals on a car implement an interface. I'm from the US where we drive on the right side of the road. Our steering wheels are on the left side of the car. The pedals for a manual transmission from left to right are clutch -> brake -> accelerator. When I went to Ireland, the driving is reversed. Cars' steering wheels are on the right and they drive on the left side of the road... but the pedals, ah the pedals... they implemented the same interface... all three pedals were in the same order... so even if the class was different and the network that class operated on was different, i was still comfortable with the pedal interface. My brain was able to call my muscles on this car just like every other car.
Think of the numerous non-programming interfaces we can't live without. Then answer your own question.
Imagine the following basic interface which defines a basic CRUD mechanism:
interface Storable {
function create($data);
function read($id);
function update($data, $id);
function delete($id);
}
From this interface, you can tell that any object that implements it, must have functionality to create, read, update and delete data. This could by a database connection, a CSV file reader, and XML file reader, or any other kind of mechanism that might want to use CRUD operations.
Thus, you could now have something like the following:
class Logger {
Storable storage;
function Logger(Storable storage) {
this.storage = storage;
}
function writeLogEntry() {
this.storage.create("I am a log entry");
}
}
This logger doesn't care if you pass in a database connection, or something that manipulates files on disk. All it needs to know is that it can call create() on it, and it'll work as expected.
The next question to arise from this then is, if databases and CSV files, etc, can all store data, shouldn't they be inherited from a generic Storable object and thus do away with the need for interfaces? The answer to this is no... not every database connection might implement CRUD operations, and the same applies to every file reader.
Interfaces define what the object is capable of doing and how you need to use it... not what it is!
Interfaces are a form of polymorphism. An example:
Suppose you want to write some logging code. The logging is going to go somewhere (maybe to a file, or a serial port on the device the main code runs on, or to a socket, or thrown away like /dev/null). You don't know where: the user of your logging code needs to be free to determine that. In fact, your logging code doesn't care. It just wants something it can write bytes to.
So, you invent an interface called "something you can write bytes to". The logging code is given an instance of this interface (perhaps at runtime, perhaps it's configured at compile time. It's still polymorphism, just different kinds). You write one or more classes implementing the interface, and you can easily change where logging goes just by changing which one the logging code will use. Someone else can change where logging goes by writing their own implementations of the interface, without changing your code. That's basically what polymorphism amounts to - knowing just enough about an object to use it in a particular way, while allowing it to vary in all the respects you don't need to know about. An interface describes things you need to know.
C's file descriptors are basically an interface "something I can read and/or write bytes from and/or to", and almost every typed language has such interfaces lurking in its standard libraries: streams or whatever. Untyped languages usually have informal types (perhaps called contracts) that represent streams. So in practice you almost never have to actually invent this particular interface yourself: you use what the language gives you.
Logging and streams are just one example - interfaces happen whenever you can describe in abstract terms what an object is supposed to do, but don't want to tie it down to a particular implementation/class/whatever.
There are a number of reasons to do so. When you use an interface, you're ready in the future when you need to refactor/rewrite the code. You can also provide an sort of standardized API for simple operations.
For example, if you want to write a sort algorithm like the quicksort, all you need to sort any list of objects is that you can successfuuly compare two of the objects. If you create an interface, say ISortable, than anyone who creates objects can implement the ISortable interface and they can use your sort code.
If you're writing code that uses a database storage, and you write to an storage interface, you can replace that code down the line.
Interfaces encourage looser coupling of your code so that you can have greater flexibility.
In an article in my blog I briefly describe three purposes interfaces have.
Interfaces may have different
purposes:
Provide different implementations for the same goal. The typical example
is a list, which may have different
implementations for different
performance use cases (LinkedList,
ArrayList, etc.).
Allow criteria modification. For example, a sort function may accept a
Comparable interface in order to
provide any kind of sort criteria,
based on the same algorithm.
Hide implementation details. This also makes it easier for a user to
read the comments, since in the body
of the interface there are only
methods, fields and comments, no long
chunks of code to skip.
Here's the article's full text: http://weblogs.manas.com.ar/ary/2007/11/
The best Java code I have ever seen defined almost all object references as instances of interfaces instead of instances of classes. It is a strong sign of quality code designed for flexibility and change.
As you noted, interfaces are good for when you want to force someone to make it in a certain format.
Interfaces are good when data not being in a certain format can mean making dangerous assumptions in your code.
For example, at the moment I'm writing an application that will transform data from one format in to another. I want to force them to place those fields in so I know they will exist and will have a greater chance of being properly implemented. I don't care if another version comes out and it doesn't compile for them because it's more likely that data is required anyways.
Interfaces are rarely used because of this, since usually you can make assumptions or don't really require the data to do what you need to do.
An interface, defines merely the interface. Later, you can define method (on other classes), which accepted interfaces as parameters (or more accurately, object which implement that interface). This way your method can operate on a large variety of objects, whose only commonality is that they implement that interface.
First, they give you an additional layer of abstraction. You can say "For this function, this parameter must be an object that has these methods with these parameters". And you probably want to also set the meaning of these methods, in somehow abstracted terms, yet allowing you to reason about the code. In duck-typed languages you get that for free. No need for explicit, syntax "interfaces". Yet you probably still create a set of conceptual interfaces, something like contracts (like in Design by Contract).
Furthermore, interfaces are sometimes used for less "pure" purposes. In Java, they can be used to emulate multiple inheritance. In C++, you can use them to reduce compile times.
In general, they reduce coupling in your code. That's a good thing.
Your code may also be easier to test this way.
Let's say you want to keep track of a collection of stuff. Said collections must support a bunch of things, like adding and removing items, and checking if an item is in the collection.
You could then specify an interface ICollection with the methods add(), remove() and contains().
Code that doesn't need to know what kind of collection (List, Array, Hash-table, Red-black tree, etc) could accept objects that implemented the interface and work with them without knowing their actual type.
In .Net, I create base classes and inherit from them when the classes are somehow related. For example, base class Person could be inherited by Employee and Customer. Person might have common properties like address fields, name, telephone, and so forth. Employee might have its own department property. Customer has other exclusive properties.
Since a class can only inherit from one other class in .Net, I use interfaces for additional shared functionality. Sometimes interfaces are shared by classes that are otherwise unrelated. Using an interface creates a contract that developers will know is shared by all of the other classes implementing it. I also forces those classes to implement all of its members.
In C# interfaces are also extremely useful for allowing polymorphism for classes that do not share the same base classes. Meaning, since we cannot have multiple inheritance you can use interfaces to allow different types to be used. It's also a way to allow you to expose private members for use without reflection (explicit implementation), so it can be a good way to implement functionality while keeping your object model clean.
For example:
public interface IExample
{
void Foo();
}
public class Example : IExample
{
// explicit implementation syntax
void IExample.Foo() { ... }
}
/* Usage */
Example e = new Example();
e.Foo(); // error, Foo does not exist
((IExample)e).Foo(); // success
I think you need to get a good understand of design patterns so see there power.
Check out
Head First Design Patterns