Encapsulation In C# With Example

05:59
Encapsulation is most important part of Object oriented programming. Basic meaning of Encapsulation is the packing of data and functions into a single component. The features of encapsulation are supported using classes in most object-oriented programming languages. This words might seems to be complex to understand. There is one more concept called as abstraction that need to be taken care of while understanding encapsulation.

Also Read : Loop In C# Programming With An Example


Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction. Do not get confuse. Read example below.

Just take a real life example: Car is an entity/class that driver drive. Starting the car, changing hear, accelerate it and so on and so forth. Let's say in programming terms this activities like starting car, changing gears and accelerate car and break are methods. So driver know what this methods do, but he really don't know how this method works. In another words driver know by pressing the hand break or the other break car will stop. But on mechanical part of it he don't know what actually happens in engine of the car to apply the breaks.

From above example we can understand that function of the car are encapsulated in class called car for make it working from different methods like accelerate, break. Here what that methods are doing actually will abstraction. Since driver know what is the function but he/she do not know what actually happened.


Here accessibility is also an important aspect of object oriented programming,Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers:
  • public
  • private
  • protected
  • internal
If you have not noticed we have used public access specifier from first program itself. while we user main method in every code it start like this:

public static void main(string[] args)
{
//your code
}
We will see each of them how they differ with example:

Public Access specifier:

Public access specifier denote the compiler that that class methods and member variables are accessible to other function and objects. Public member can be accessible out side the class also. Let's take an example: We will create 2 class one is Circle and another is executecircle :

using System;
using System.Collections.Generic;
namespace Encapsulatio_Demo
{
    class Circle
    {
        //member variable of class circle
        public double radius ;
        const double pi = 3.1421; // this is constant variable in C# it's value once assign cannot be changed.
        public double AreaOfCircle()
        {
            return  pi * (redius * redius);
        }
        public void display()
        {
            Console.WriteLine("Area of the Circle "+AreaOfCircle()+" having Radius "+radius );
        }
    } 
    class ExecuteCircle
    {
        static void Main(string[] args)
        {
            Circle c = new Circle();
            c.radius = 10;
            c.display();
            Console.ReadLine();
        }
    }
}
Output will Be as follows:
Area of the Circle 314.21 having Radius 10 
In the above example Class Circle variables and method are declared as public. Hence they can be accessible in class ExecuteCircle. We have access the radius variable through object of class Circle i.e c.radius = 10; Here we are assigning the of radius. We have also displayed the output using Circle class method from c.display();

Private Access specifier:

Private access specifier do not allow other class or functions or objects to access their member variable and functions. Only function of the same class can access  it's private members. Let's take same example. Here is code:
using System;
using System.Collections.Generic;
namespace Encapsulatio_Demo
{
    class Circle
    {
        //member variable of class circle
        public double radius=10 ;
        const double pi = 3.1421; // this is constant variable in C# it's value once assign cannot be changed.
        public double AreaOfCircle()
        {
            return  pi * (redius * redius);
        }
        public void display()
        {
            Console.WriteLine("Area of the Circle "+AreaOfCircle()+" having Radius "+radius );
        }
    } 
    class ExecuteCircle
    {
        static void Main(string[] args)
        {
            Circle c = new Circle();
            c.AreaOfCircle();
            c.display();
            Console.ReadLine();
        }
    }
}

Output will Be as follows:
Area of the Circle 314.21 having Radius 10 
Here is we have not change much since methods cannot be private, because if we make them private they even cannot accessible by object of the same class. So methods have no meaning. If you try c.redius=10; this line will give an error and will not execute. Since we have marked it private. Try and change method accessibility as private then in second class where you are calling methods will be shown as error. Since private methods cannot be accessible outside the class Circle.

Protected Access Specifier:

Protected access specifier allow the child class to access access it's base class member variable and methods. We will see in detail in upcoming concept of Inheritance.

Internal Access Specifier:

Internal access specifier expose the classes exist in the same namespace or some call it as assembly. You can access one variable in another class present in same assembly once that variable is makerd internal. Check the output of below program for the same:
using System;
using System.Collections.Generic;
namespace Encapsulatio_Demo
{
    class Circle
    {
        //member variable of class circle
        internal double radius;
        const double pi = 3.1421; // this is constant variable in C# it's value once assign cannot be changed.
        public double AreaOfCircle()
        {
            return pi * (radius * radius);
        }
        public void display()
        {
            Console.WriteLine("Area of the Circle " + AreaOfCircle() + " having Radius " + radius);
        }
    }
    class ExecuteCircle
    {
        static void Main(string[] args)
        {
            Circle c = new Circle();
            c.radius = 10;
            c.display();
            Console.ReadLine();
        }
    }
}

Output will Be as follows:
Area of the Circle 314.21 having Radius 10  
So here we have done with concept of encapsulation. Don't miss our upcoming tutorial.  This are very important concept. This is concept on which interviewer will play with your mind. Stay tuned for more. You have any query or suggestion do comment below. Thank you for reading.

Share this

CEO and Admin of TechnoDiscover And Nothing Like Everything
Bcom From Mumbai University
Pursuing MCA From Mumbai University

Related Posts

Previous
Next Post »