The object oriented programming will give theimpression very unnatural to a programmer with a lot of proceduralprogramming experience. In Object Oriented programming Encapsulation isthe first pace. Encapsulation is the procedure of covering up of dataand functions into a single unit (called class). An encapsulated objectis often called an abstract data type. In this article let us see aboutit in a detailed manner.
NEED FOR ENCAPSULATION:
The need of encapsulation is to protect orprevent the code (data) from accidental corruption due to the sillylittle errors that we are all prone to make. In Object orientedprogramming data is treated as a critical element in the programdevelopment and data is packed closely to the functions that operate onit and protects it from accidental modification from outside functions.
Encapsulation provides a way to protect datafrom accidental corruption. Rather than defining the data in the formof public, we can declare those fields as private. The Private data aremanipulated indirectly by two ways. Let us see some example programs inC# to demonstrate Encapsulation by those two methods. The first methodis using a pair of conventional accessor and mutator methods. Anotherone method is using a named property. Whatever be the method our aim isto use the data with out any damage or change.
ENCAPSULATION USING ACCESSORS AND MUTATORS:
Let us see an example of Department class. Tomanipulate the data in that class (String departname) we define anaccessor (get method) and mutator (set method).
public class Department
private string departname;
public string GetDepartname()
public void SetDepartname( string a)
Like the above way we can protect the privatedata from the outside world. Here we use two separate methods to assignand get the required data.
public static int Main(string args)
Department d = new Department();
Console.WriteLine(“The Department is :”+d.GetDepartname());
In the above example we can’t access theprivate data departname from an object instance. We manipulate the dataonly using those two methods.
ENCAPSULATION USING PROPERTIES:
Properties are a new language featureintroduced with C#. Only a few languages support this property.Properties in C# helps in protect a field in a class by reading andwriting to it. The first method itself is good but Encapsulation can beaccomplished much smoother with properties.Now let’s see an example.
Pages: 1 2