What are the different types of encapsulation? - oop

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

Related

Confusion with understanding abstraction and encapsulation in OOP

I was learning JS and came across the term OOP. Then, as I was learning OOP and I found such concepts as abstraction and encapsulation. Moreover, as I was making researching on the difference between them, majority of articles says that both abstraction and encapsulation are concerned with data hiding which confused me very much. However, I made an inference that encapsulation is when we just put variables and functions that operate on them in OBJECT while abstraction is when we use access modifiers to restrict access to properties or functions in an object. Again, encapsulation is when we use capsule like object and put variables and functions in it to achieve organization and reusability. But abstraction is when we restrict access to variables and functions inside object. IS THAT TRUE?
Encapsulation means that you protect your data inside your class (or object) for the outer world and like you say you access the private or protected data via methods (functions) from the same object.
Abstraction is something totally different. Lets take an example.
Imagine that you want to use constraints on your form fields. For example you have a formfield 'email' which may not be empty and must contain an valid email.
So you want to add different kind of constraints to a large number of form fields all over your application.
All constraints must have two methods:
1) a method that tests the formfield data if it is valid
2) a method that delivers an error message if the data is not valid
Now before you write all those different constraint objects you could write one ABSTRACT parent class That includes those two methods but without any code:
(I use PHP)
abstract class Constraint
{
// Force Extending classes to define this methods
abstract protected function validate(string $data);
abstract protected function getErrorMessage();
}
Above class is abstract and cannot be used (instantiated) by its self. But you can write different constraint classes that inherit the above class:
class NotEmptyConstraint extends Constraint
{
// Mandatory overwritten methods:
protected function validate(string $data)
{
if(strlen($data) > 0 ) {
return true;
}
return false;
}
protected function getErrorMessage();
{
return 'This is a mandatory field';
}
}
Now all your constraint classes have the two mandatory methods which you can safely use without you need to know which exact constraint your dealing with.
Hope it helps..
OOP is dogma.
The author of this website wrote an article on abstraction and why it doesn't work: https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/
In other words, cell phones and LAN phones are not based on the same hardcoded abstraction of a phone. They are free to be their own classes. Barbara Liskov (SOLID) would argue each are subtypes. I strongly discourage tying your hands by creating such arbitrary hierarchical categorization schemes. This is not how real machines are engineered. Refer to fundamental principles of mechanical design, which dictate simplicity of design, meaning less components when feasible. A separate abstract class is a waste of time and distributes the design itself into two modules.
Encapsulation is the fallacious idea that objects own the data they operate on and, therefore, must control access to it. This notion is disproven by manufacturing's model for collaborative work, which is what my architecture is based on. A screwdriver doesn't own a screw simply because it changes its position. It simply has access to it.
OOP and encapsulation led to the distributed process code model. Objects e-mail work to one another like useless office employees who don't keep e-mail trails. If you've ever gotten e-mail from people asking for help who don't give you any information, then you understand my parody. In manufacturing, steps are documented and never communicate, which creates tremendous benefits. OOP is only enough know-how to write monolithic automated processes, not processes which stop on a dime, reverse, can insert or replace steps on the fly, and try steps again. OOP is a model for distributed manufacturing, whereas manufacturing is a model for organizing everyone who creates some product in the same space.

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 in Information hiding and data abstraction?

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.

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

Is Inheritance really needed?

I must confess I'm somewhat of an OOP skeptic. Bad pedagogical and laboral experiences with object orientation didn't help. So I converted into a fervent believer in Visual Basic (the classic one!).
Then one day I found out C++ had changed and now had the STL and templates. I really liked that! Made the language useful. Then another day MS decided to apply facial surgery to VB, and I really hated the end result for the gratuitous changes (using "end while" instead of "wend" will make me into a better developer? Why not drop "next" for "end for", too? Why force the getter alongside the setter? Etc.) plus so much Java features which I found useless (inheritance, for instance, and the concept of a hierarchical framework).
And now, several years afterwards, I find myself asking this philosophical question: Is inheritance really needed?
The gang-of-four say we should favor object composition over inheritance. And after thinking of it, I cannot find something you can do with inheritance you cannot do with object aggregation plus interfaces. So I'm wondering, why do we even have it in the first place?
Any ideas? I'd love to see an example of where inheritance would be definitely needed, or where using inheritance instead of composition+interfaces can lead to a simpler and easier to modify design. In former jobs I've found if you need to change the base class, you need to modify also almost all the derived classes for they depended on the behaviour of parent. And if you make the base class' methods virtual... then not much code sharing takes place :(
Else, when I finally create my own programming language (a long unfulfilled desire I've found most developers share), I'd see no point in adding inheritance to it...
Really really short answer: No. Inheritance is not needed because only byte code is truly needed. But obviously, byte code or assemble is not a practically way to write your program. OOP is not the only paradigm for programming. But, I digress.
I went to college for computer science in the early 2000s when inheritance (is a), compositions (has a), and interfaces (does a) were taught on an equal footing. Because of this, I use very little inheritance because it is often suited better by composition. This was stressed because many of the professors had seen bad code (along with what you have described) because of abuse of inheritance.
Regardless of creating a language with or without inheritances, can you create a programming language which prevents bad habits and bad design decisions?
I think asking for situations where inheritance is really needed is missing the point a bit. You can fake inheritance by using an interface and some composition. This doesnt mean inheritance is useless. You can do anything you did in VB6 in assembly code with some extra typing, that doesn't mean VB6 was useless.
I usually just start using an interface. Sometimes I notice I actually want to inherit behaviour. That usually means I need a base class. It's that simple.
Inheritance defines an "Is-A" relationship.
class Point( object ):
# some set of features: attributes, methods, etc.
class PointWithMass( Point ):
# An additional feature: mass.
Above, I've used inheritance to formally declare that PointWithMass is a Point.
There are several ways to handle object P1 being a PointWithMass as well as Point. Here are two.
Have a reference from PointWithMass object p1 to some Point object p1-friend. The p1-friend has the Point attributes. When p1 needs to engage in Point-like behavior, it needs to delegate the work to its friend.
Rely on language inheritance to assure that all features of Point are also applicable to my PointWithMass object, p1. When p1 needs to engage in Point-like behavior, it already is a Point object and can just do what needs to be done.
I'd rather not manage the extra objects floating around to assure that all superclass features are part of a subclass object. I'd rather have inheritance to be sure that each subclass is an instance of it's own class, plus is an instance of all superclasses, too.
Edit.
For statically-typed languages, there's a bonus. When I rely on the language to handle this, a PointWithMass can be used anywhere a Point was expected.
For really obscure abuse of inheritance, read about C++'s strange "composition through private inheritance" quagmire. See Any sensible examples of creating inheritance without creating subtyping relations? for some further discussion on this. It conflates inheritance and composition; it doesn't seem to add clarity or precision to the resulting code; it only applies to C++.
The GoF (and many others) recommend that you only favor composition over inheritance. If you have a class with a very large API, and you only want to add a very small number of methods to it, leaving the base implementation alone, I would find it inappropriate to use composition. You'd have to re-implement all of the public methods of the encapsulated class to just return their value. This is a waste of time (programmer and CPU) when you can just inherit all of this behavior, and spend your time concentrating on new methods.
So, to answer your question, no you don't absolutely need inheritance. There are, however, many situations where it's the right design choice.
The problem with inheritance is that it conflates the issue of sub-typing (asserting an is-a relationship) and code reuse (e.g., private inheritance is for reuse only).
So, no it's an overloaded word that we don't need. I'd prefer sub-typing (using the 'implements' keyword) and import (kinda like Ruby does it in class definitions)
Inheritance lets me push off a whole bunch of bookkeeping onto the compiler because it gives me polymorphic behavior for object hierarchies that I would otherwise have to create and maintain myself. Regardless of how good a silver bullet OOP is, there will always be instances where you want to employ a certain type of behavior because it just makes sense to do. And ultimately, that's the point of OOP: it makes a certain class of problems much easier to solve.
The downsides of composition is that it may disguise the relatedness of elements and it may be harder for others to understand. With,say, a 2D Point class and the desire to extend it to higher dimensions, you would presumably have to add (at least) Z getter/setter, modify getDistance(), and maybe add a getVolume() method. So you have the Objects 101 elements: related state and behavior.
A developer with a compositional mindset would presumably have defined a getDistance(x, y) -> double method and would now define a getDistance(x, y, z) -> double method. Or, thinking generally, they might define a getDistance(lambdaGeneratingACoordinateForEveryAxis()) -> double method. Then they would probably write createTwoDimensionalPoint() and createThreeDimensionalPoint() factory methods (or perhaps createNDimensionalPoint(n) ) that would stitch together the various state and behavior.
A developer with an OO mindset would use inheritance. Same amount of complexity in the implementation of domain characteristics, less complexity in terms of initializing the object (constructor takes care of it vs. a Factory method), but not as flexible in terms of what can be initialized.
Now think about it from a comprehensibility / readability standpoint. To understand the composition, one has a large number of functions that are composed programmatically inside another function. So there's little in terms of static code 'structure' (files and keywords and so forth) that makes the relatedness of Z and distance() jump out. In the OO world, you have a great big flashing red light telling you the hierarchy. Additionally, you have an essentially universal vocabulary to discuss structure, widely known graphical notations, a natural hierarchy (at least for single inheritance), etc.
Now, on the other hand, a well-named and constructed Factory method will often make explicit more of the sometimes-obscure relationships between state and behavior, since a compositional mindset facilitates functional code (that is, code that passes state via parameters, not via this ).
In a professional environment with experienced developers, the flexibility of composition generally trumps its more abstract nature. However, one should never discount the importance of comprehensibility, especially in teams that have varying degrees of experience and/or high levels of turnover.
Inheritance is an implementation decision. Interfaces almost always represent a better design, and should usually be used in an external API.
Why write a lot of boilerplate code forwarding method calls to a composed member object when the compiler will do it for you with inheritance?
This answer to another question summarises my thinking pretty well.
Does anyone else remember all of the OO-purists going ballistic over the COM implementation of "containment" instead of "inheritance?" It achieved essentially the same thing, but with a different kind of implementation. This reminds me of your question.
I strictly try to avoid religious wars in software development. ("vi" OR "emacs" ... when everybody knows its "vi"!) I think they are a sign of small minds. Comp Sci Professors can afford to sit around and debate these things. I'm working in the real world and could care less. All of this stuff are simply attempts at giving useful solutions to real problems. If they work, people will use them. The fact that OO languages and tools have been commercially available on a wide scale for going on 20 years is a pretty good bet that they are useful to a lot of people.
There are a lot of features in a programming language that are not really needed. But they are there for a variety of reasons that all basically boil down to reusability and maintainability.
All a business cares about is producing (quality of course) cheaply and quickly.
As a developer you help do this is by becoming more efficient and productive. So you need to make sure the code you write is easily reusable and maintainable.
And, among other things, this is what inheritance gives you - the ability to reuse without reinventing the wheel, as well as the ability to easily maintain your base object without having to perform maintenance on all similar objects.
There's lots of useful usages of inheritance, and probably just as many which are less useful. One of the useful ones is the stream class.
You have a method that should be able stream data. By using the stream base class as input to the method you ensure that your method can be used to write to many kinds of streams without change. To the file system, over the network, with compression, etc.
No.
for me, OOP is mostly about encapsulation of state and behavior and polymorphism.
and that is. but if you want static type checking, you'll need some way to group different types, so the compiler can check while still allowing you to use new types in place of another, related type. creating a hierarchy of types lets you use the same concept (classes) for types and for groups of types, so it's the most widely used form.
but there are other ways, i think the most general would be duck typing, and closely related, prototype-based OOP (which isn't inheritance in fact, but it's usually called prototype-based inheritance).
Depends on your definition of "needed". No, there is nothing that is impossible to do without inheritance, although the alternative may require more verbose code, or a major rewrite of your application.
But there are definitely cases where inheritance is useful. As you say, composition plus interfaces together cover almost all cases, but what if I want to supply a default behavior? An interface can't do that. A base class can. Sometimes, what you want to do is really just override individual methods. Not reimplement the class from scratch (as with an interface), but just change one aspect of it. or you may not want all members of the class to be overridable. Perhaps you have only one or two member methods you want the user to override, and the rest, which calls these (and performs validation and other important tasks before and after the user-overridden methods) are specified once and for all in the base class, and can not be overridden.
Inheritance is often used as a crutch by people who are too obsessed with Java's narrow definition of (and obsession with) OOP though, and in most cases I agree, it's the wrong solution, as if the deeper your class hierarchy, the better your software.
Inheritance is a good thing when the subclass really is the same kind of object as the superclass. E.g. if you're implementing the Active Record pattern, you're attempting to map a class to a table in the database, and instances of the class to a row in the database. Consequently, it is highly likely that your Active Record classes will share a common interface and implementation of methods like: what is the primary key, whether the current instance is persisted, saving the current instance, validating the current instance, executing callbacks upon validation and/or saving, deleting the current instance, running a SQL query, returning the name of the table that the class maps to, etc.
It also seems from how you phrase your question that you're assuming that inheritance is single but not multiple. If we need multiple inheritance, then we have to use interfaces plus composition to pull off the job. To put a fine point about it, Java assumes that implementation inheritance is singular and interface inheritance can be multiple. One need not go this route. E.g. C++ and Ruby permit multiple inheritance for your implementation and your interface. That said, one should use multiple inheritance with caution (i.e. keep your abstract classes virtual and/or stateless).
That said, as you note, there are too many real-life class hierarchies where the subclasses inherit from the superclass out of convenience rather than bearing a true is-a relationship. So it's unsurprising that a change in the superclass will have side-effects on the subclasses.
Not needed, but usefull.
Each language has got its own methods to write less code. OOP sometimes gets convoluted, but I think that is the responsability of the developers, the OOP platform is usefull and sharp when it is well used.
I agree with everyone else about the necessary/useful distinction.
The reason I like OOP is because it lets me write code that's cleaner and more logically organized. One of the biggest benefits comes from the ability to "factor-up" logic that's common to a number of classes. I could give you concrete examples where OOP has seriously reduced the complexity of my code, but that would be boring for you.
Suffice it to say, I heart OOP.
Absolutely needed? no,
But think of lamps. You can create a new lamp from scratch each time you make one, or you can take properties from the original lamp and make all sorts of new styles of lamp that have the same properties as the original, each with their own style.
Or you can make a new lamp from scratch or tell people to look at it a certain way to see the light, or , or, or
Not required, but nice :)
Thanks to all for your answers. I maintain my position that, strictly speaking, inheritance isn't needed, though I believe I found a new appreciation for this feature.
Something else: In my job experience, I have found inheritance leads to simpler, clearer designs when it's brought in late in the project, after it's noticed a lot of the classes have much commonality and you create a base class. In projects where a grand-schema was created from the very beginning, with a lot of classes in an inheritance hierarchy, refactoring is usually painful and dificult.
Seeing some answers mentioning something similar makes me wonder if this might not be exactly how inheritance's supposed to be used: ex post facto. Reminds me of Stepanov's quote: "you don't start with axioms, you end up with axioms after you have a bunch of related proofs". He's a mathematician, so he ought to know something.
The biggest problem with interfaces is that they cannot be changed. Make an interface public, then change it (add a new method to it) and break million applications all around the world, because they have implemented your interface, but not the new method. The app may not even start, a VM may refuse to load it.
Use a base class (not abstract) other programmers can inherit from (and override methods as needed); then add a method to it. Every app using your class will still work, this method just won't be overridden by anyone, but since you provide a base implementation, this one will be used and it may work just fine for all subclasses of your class... it may also cause strange behavior because sometimes overriding it would have been necessary, okay, might be the case, but at least all those million apps in the world will still start up!
I rather have my Java application still running after updating the JDK from 1.6 to 1.7 with some minor bugs (that can be fixed over time) than not having it running it at all (forcing an immediate fix or it will be useless to people).
//I found this QA very useful. Many have answered this right. But i wanted to add...
1: Ability to define abstract interface - E.g., for plugin developers. Of course, you can use function pointers, but this is better and simpler.
2: Inheritance helps model types very close to their actual relationships. Sometimes a lot of errors get caught at compile time, because you have the right type hierarchy. For instance, shape <-- triangle (lets say there is a lot of code to be reused). You might want to compose triangle with a shape object, but shape is an incomplete type. Inserting dummy implementations like double getArea() {return -1;} will do, but you are opening up room for error. That return -1 can get executed some day!
3: void func(B* b); ... func(new D()); Implicit type conversion gives a great notational convenience since Derived is Base. I remember having read Straustrup saying that he wanted to make classes first class citizens just like fundamental data types (hence overloading operators etc). Implicit conversion from Derived to Base, behaves just like an implicit conversion from a data type to broader compatible one (short to int).
Inheritance and Composition have their own pros and cons.
Refer to this related SE question on pros of inheritance and cons of composition.
Prefer composition over inheritance?
Have a look at the example in this documentation link:
The example shows different use cases of overriding by using inheritance as a mean to achieve polymorphism.
In the following, inheritance is used to present a particular property for all of several specific incarnations of the same type thing. In this case, the GeneralPresenation has a properties that are relevant to all "presentation" (the data passed to an MVC view). The Master Page is the only thing using it and expects a GeneralPresentation, though the specific views expect more info, tailored to their needs.
public abstract class GeneralPresentation
{
public GeneralPresentation()
{
MenuPages = new List<Page>();
}
public IEnumerable<Page> MenuPages { get; set; }
public string Title { get; set; }
}
public class IndexPresentation : GeneralPresentation
{
public IndexPresentation() { IndexPage = new Page(); }
public Page IndexPage { get; set; }
}
public class InsertPresentation : GeneralPresentation
{
public InsertPresentation() {
InsertPage = new Page();
ValidationInfo = new PageValidationInfo();
}
public PageValidationInfo ValidationInfo { get; set; }
public Page InsertPage { get; set; }
}