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

  1. using system;  
  2. public class Department {  
  3.     private string departname;  
  4.     public string Departname {  
  5.         get {  
  6.             return departname;  
  7.         }  
  8.         set {  
  9.             departname = value;  
  10.         }  
  11.     }  
  12. }  
  13. public class Departmentmain {  
  14.     public static int Main(string[] args) {  
  15.         Department d = new Department();  
  16.         d.departname = "Communication";  
  17.         Console.WriteLine("The Department is :{0}", d.Departname);  
  18.         return 0;  
  19.     }  

Leave Comment

Important Topics

Title
Object Oriented Programming (OOP)
OOP vs POP
Class with Example
Objects
Access Modifiers
Encapsulation with example
C# Properties (GET, SET)
Method and Function
Abstraction
Polymorphism
Operator Overloading
Inheritance
Constructor and its Types
Exception Handling
Throwing an Exception