Pages

SPONSORED

What do you mean by Encapsulation?

As the name suggests Encapsulation means keeping all the objects data is contained together within the object. Data of object here refers to its variables and methods. Object hides the inner implementation from the outside view. Encapsulation controls interactions of objects. It prevents object interaction in unexpected way. This improves code modularity as well as improves application security.
 
Encapsulation Example


Class Product{
private double cost = 0.0;

public void setCost(double cost){
if(cost > 0)
this.cost = cost;
else
throw new Exception("No negative Values for Cost");
}

public int getCost(){
return cost;
}
}

The sample code above shows how the value of cost of the product is controlled. The value of cost can be set only via setCost method which takes care to avoid negative values to be set for the variable.Secure member can be modified in this manner and can be helful to control the code from insecure access.

Access modifiers are keywords used to specify the declared accessibility of a member or a type. The following are access modifiers for C++, C# and Java.
C# and C++
Public: All Objects can access it.
Protected: Access is limited to members of the same class or descendants.
Private: Access is limited to members of the same class.
Internal: Access is limited to the current assembly.
Protected Internal: Access is limited to the current assembly or types derived from the containing class.

The first 3 access levels are available both in C# and C++. But the last 2 are available only in C#.

Java
Public: All Objects can access it.
Protected: Access is limited to members of other classes within the same package or descendants.
Private: Access is limited to members of the same class.
No Modifier: Access is limited to the current package.

Benefits
Maintainability: Encapsulation helps increases the maintainability of the code and reduces the refactoring effort.
Security: It increases security by avoiding objects interaction in unexpected way. This will protect the variables from unaccepted values.

No comments:

Post a Comment