Encapsulation in Object-Oriented Programming(OOPS)
This is the key features of OOPs but I would like to tell you that Encapsulation is also possible in non-object oriented programming languages like C. In OOPs Encapsulation
is used to hide the values or state of a structured data object inside a class
, preventing unauthorized parties' direct access to them.
Encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components.
Use of Encapsulation
Encapsulation provides a way to protect data from accidental corruption.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 in C#
The process of binding the data and functions/method together into a single unit (this is called class) is called encapsulation in C#.
. We can achieve this feature in C# with below mthods:
Encapsulation using ACCESSORS and MUTATORS in C#
In below example we have a class Company in which we have private member companyName
and to manipulate we have get and set method.
public class Company { private string companyName; // Accessor. public string GetCompanyName() { return companyName; } // Mutator. public void SetCompanyName(string a) { companyName = a; } }
Encapsulation using PROPERTIES in C#
Encapsulation can be accomplished much smoother with properties as this helps in protect a field in a class by reading and writing to it.
public class Company { private string companyName; public string Companyname { get { return companyName; } set { companyName = value; } } }
Please note that we can have read-only or write-only property in above class depend on our requirement.
Summary
To summarise, The Encapsulation is the first footstep towards the object-oriented programming. This article gives you a little bit information about Encapsulation. Hope you picked up a thing or two.
Cheers!