There are four major properties of Object Oriented Programming (OOPs) as you know. These are:
Among of these four properties or features, we will discuss the first two (Abstraction and Encapsulation) in this post.
So what actually are Abstraction and Encapsulation? Let us find out with an example.
Abstraction is a process to abstract or hide the functionality and provide users or other programmers to use it only. Like for the method
Console.WriteLine(), no one knows what actually is happening behind the function calling. We are just using it by calling and passing the arguments. This is the thing called Abstraction.
Encapsulation means to encapsulate or put everything into one thing and provide others to use it. Like in a shaving kit, all the necessary kits are available. And also these kits are available as loose in market. But the shaving kit encapsulates every other kit into a small bag and provides a user to use it.
Hope you now have a basic idea about both of these properties. Let's see a real world example of encapsulation and abstraction.
Let's assume you have to create a method to insert users data and pass it to other developers to use. So first, create a class and add a method to insert the data into database with validation.
There will be three fields:
- Phone number
So these inputs have to validate first and then insert into db.
First, create a class with all methods:
public bool AddUser(string name, string email, string phone)
if (ValidateUser(name, email, phone))
if (AddtoDb(name, email, phone) > 0)
private bool ValidateUser(string name, string email, string phone)
private int AddtoDb(string name, string email, string phone)
As you can see, there are three methods that are written in this
AddUser: To call from outside the class. That is why the access modifier is
validateUser: To validate the user's details. Can't access from outside the class. It's
AddtoDb: To insert data into database table and again it is
private, can't access from outside the class.
Now another user will just call
AddUser method with parameters. And that user has no idea what is actually happening inside the method. I didn't write the code to validate and insert into db, as you can get it from others examples. We will discuss about it later.
To call the
AddUser method, do as follows:
static void Main(string args)
User objUser = new User();
bool f = objUser.AddUser("Arka", "firstname.lastname@example.org", "1234567890");
Now come back to the main discussion.
Here, we are hiding the procedure of adding data into database from other users, this is Abstraction. And putting all the three methods into one
User class and providing other users to use it, that is called Encapsulation.
So procedure hiding is Abstraction and putting every necessary thing into one is Encapsulation.
Hope you have cleared your doubts about the concepts of Encapsulation and Abstraction. CodeProject