Encapsulation in OOPs.

Encapsulation is the ability of an object oriented language (C# in this context) to hide unnecessary implementation details from the object user. Encapsulation makes coding simpler and helps to preserve data integrity.

According to the concept of encapsulation, an object’s internal data should not be directly accessible from an object instance. Members of a class that represent an object’s state should not be marked as public. The state of an object should only be altered indirectly by using public members. C# prefers properties to encapsulate data.

Ex.

class ABC
{
// private data members
private int roll;
private int class;
private string name;
// public properties
public int Roll
{
get { return roll; }
set { roll = value; }
}
public int Class
{
get { return class; }
set { class = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
// constructor
public ABC()
{
// values are assigned to data members via properties
Roll = 10;
Class = 9;
Name = “Sunil Kumar Meena”;
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s