C# Encapsulation Explanation with Example
Hello everyone, In this article we are going to talk about encapsulation in Object oriented programming. We will make an example in C# and Visual studio to understand it better.Lets get started
Firstly, What is Encapsulation
Encapsulation is protecting objects or methods in a class from out of this class. Thanks to Encapsulation we prevent the other classes to access the items which we do not want to show. In a class we use necessary modifier word in definition to specify the eccess level and only related class can access to this variables or objects.
We can use below modifier words :
- Public : This access modifier lets the class to show the variable or function to the other classes. All public objects can be reached from all class.
- Private : This access modifier set the variable or the method to hide from outside of class. Only the related class can use these items.
- Protected : This modifier allows a derived class to access a variable or a method which defined in upper class.
- Internal : This modifier let the class to use a variable or method to be used in the app or package.
- Protected Internal : This modifier lets the variable or method to be hidden from the accesser. Only child class can access to this variable or method.
Below code block, I created a class named Employee and I have declared all variable types above:
using System;
namespace CSharp_Encapsulation
{
class Employee
{
public string public_variable = "public";
private string private_variable = "private";
protected string protected_variable = "protected";
internal string internal_variable = "internal";
protected internal string pro_internal = "pro_internal";
}
}
Now I will try to use them from another class, Below image you will see you can not use the private and protected defined variables here :
Below code block you will see the code block to call these variables.
private void Form1_Load(object sender, EventArgs e)
{
Employee emp = new Employee();
emp.internal_variable = " new internal variable value ";
emp.pro_internal = " new pro variable value ";
emp.public_variable = "new_public variable value ";
}
That is all in this article.
Have a good encapsulation
Burak Hamdi TUFAN
Comments