latest Post

Encapsulation in C#

The object oriented programming will give the impression very unnatural to a programmer with a lot of procedural programming experience. In Object Oriented programming Encapsulation is the first place. Encapsulation is the procedure of covering up of data and functions into a single unit (called class). An encapsulated object is often called an abstract data type. In this article let us see about it in a detailed manner.

NEED FOR ENCAPSULATION

The need of encapsulation is to protect or prevent the code (data) from accidental corruption due to the silly little errors that we are all prone to make. In Object oriented programming data is treated as a critical element in the program development and data is packed closely to the functions that operate on it and protects it from accidental modification from outside functions.

Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in the form of public, we can declare those fields as private. The Private data are manipulated indirectly by two ways. Let us see some example programs in C# to demonstrate Encapsulation by those two methods. The first method is using a pair of conventional accessor and mutator methods. Another one method is using a named property. Whatever be the method our aim is to use the data without any damage or change.

ENCAPSULATION USING ACCESSORS AND MUTATORS

Let us see an example of Department class. To manipulate the data in that class (String departname) we define an accessor (get method) and mutator (set method).
using system; 
public class Department 

    private string departname; 
    ....... 
    // Accessor. 
    public string GetDepartname() 
        { 
            return departname; 
        } 
        // Mutator. 
    public void SetDepartname(string a) 
    { 
        departname = a; 
    } 

Like the above way we can protect the private data from the outside world. Here we use two separate methods to assign and get the required data.
public static int Main(string[] args)  

    Department d = new Department(); 
    d.SetDepartname("ELECTRONICS"); 
    Console.WriteLine("The Department is :" + d.GetDepartname()); 
    return 0; 

In the above example we can't access the private data departname from an object instance. We manipulate the data only using those two methods.

About Mallikarjun A

Mallikarjun A
Recommended Posts × +

0 comments:

Post a Comment