Saturday, May 22, 2010

Data Encapsulation

Data Encapsulation is the process of combining data and functions into a single unit called class. By this method one cannot access the data directly. Data is accessible only through the functions present inside the class.

  • Data Encapsulation gave rise to the important concept of data hiding.
  • Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required
  • Encapsulation gives us maintainability, flexibility and extensibility to our code.
  • Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods.

Example on Data Encapsulation

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
class emp
{
int sal, bonus, ts;
public void tsal()
{
sal = 5000;
bonus = 300;
ts = sal + bonus;
MessageBox.Show(ts.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
emp e1 = new emp();
e1.tsal();
}
}

You concentrate on public method tsal(), change this method to private. here comes encapsulation concept hiding methods from outside world.

No comments:

Post a Comment