Tuesday, June 4, 2013

Encapsulation

Encapsulation is a combination of 2 concepts.

The first one is encapsulating a set of related methods properties into a single unit so that it can be exposed as a single instance to the external world. In C# this is implemented using the concept of classes. A class allows us to group a set of related variables and methods into a single unit and they can be accessed by creating a single instance of the class.

The second one is data hiding, i.e showing only the required details to the external world and hiding the other details which are not required to be exposed. Again this is implemented using classes and a set of access modifiers.
Access modifiers help in hiding variables and methods from the external world, for example when a variable or method is declared private then it is hidden, it can be accessed only from within the class, when viewed from outside this method/function is not visible.


The following class explains both the concepts of Encapsulation.

First the class encapsulates all employee related information like Name, Age and method to calculate salary into a single employee class.

Second it hides the variables strName, nAge and the function
calculateEmployeeSalery by marking them as private and shows only the required details to the outside world.

        // Abstraction & Encapsulation
        public class clsEmployee
        {
            // private variables Hidden from outside
            private string strName;
            private int nAge;
            //
            // Public Properties
            public string Name
            {
                get
                {
                    return strName;
                }
                set
                {
                    strName = value;
                }
            }
            public int Age
            {
                get
                {
                    return nAge;
                }
                set
                {
                    nAge = value;
                }
            }
            //
            // Public Methods
            public int getEmployeeSalery(int empId)
            {
                return calculateEmployeeSalery(empId);
            }
            //
            private int calculateEmployeeSalery(int empId)
            {
                int nSalery = 0;
                // Logic to calculate Salery
                return nSalery;
            }

        }

Search Flipkart Products:
Flipkart.com

No comments: