Encapsulation with example
What is encapsulation ? Support your answers with proper example.
In an Object Oriented programming language, encapsulation is one of the key language features. Encapsulation is the procedure of encapsulating data and functions into a single unit (called class).Encapsulation is a mechanism of binding the member data and member function in a single unit. 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 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 is:
- Binding the data with the code that manipulates it.
- It keeps the data and the code safe from external interference
- Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared.
- As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
- Encapsulation can be achieved by: Declaring all the variables in the class as private and using C# Properties in the class to set and get the values of variables.
Example of encapsulation
- using system;
- public class Department {
- private string departname;
- public string Departname {
- get {
- return departname;
- }
- set {
- departname = value;
- }
- }
- }
- public class Departmentmain {
- public static int Main(string[] args) {
- Department d = new Department();
- d.departname = "Communication";
- Console.WriteLine("The Department is :{0}", d.Departname);
- return 0;
- }
- }