Tuesday, July 31, 2018

OOPS Questions - Encapsulation and Abstraction in Simple Terms with Example



Encapsulation

Encapsulation means to encapsulate or put everything into one thing and provide others to use it.
Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Encapsulation means hiding the internal details of an object, i.e. how an object does something.

Abstraction

Abstraction is a process to abstract or hide the functionality and provide users or other programmer which are necessary,
Abstraction is "To represent the essential feature without representing the back ground details.
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.

Example

Let's assume you have to create a method to insert user’s 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:
1.       Name
2.       Email
3.       Phone number

Before insert into DB We will validate it.
First, create a class with all methods:

class User
{
    public bool AddUser(string name, string email, string phone)
    {
        if (ValidateUser(name, email, phone))
        {
            if (AddtoDb(name, email, phone) > 0)
            {
                return true;
            }
        }
        return false;
    }

    private bool ValidateUser(string name, string email, string phone)
    {
        // do your validation
        return true;
    }

    private int AddtoDb(string name, string email, string phone)
    {
        // Write the Db code to insert the data
        return 1;
    }
}

As you can see, there are three methods that are written in this User class.
·         AddUser: To call from outside the class. That is why the access modifier is public.

·         validateUser: To validate the user's details. Can't access from outside the class. It's private.

·         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
To call the AddUser method, do as follows:

class Program
{
    static void Main(string[] args)
    {
        User objUser = new User();
        bool f = objUser.AddUser("John", "john@abc.com", "34354543455");
    }
}
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.

Featured Post