|
|
| Encapsulation
|
|
Overloading is nothing but " Information Hiding (or) Data Hiding " .
|
Encapsulation is the concept of hiding the implementation details of a class and allowing access to the class through
a public interface. For this, we need to declare the instance variables of the class as private or protected.
The client code should access only the public methods rather than accessing the data directly. Also, the methods
should follow the Java Bean's naming convention of set and get.
Encapsulation makes it easy to maintain and modify code. The client code is not affected when the internal
implementation of the code changes as long as the public method signatures are unchanged.
For instance:
public class Employee
{
private float salary;
public float getSalary()
{
return salary;
}
public void setSalary(float salary)
{
this.salary = salary;
}
|
Real Time Example:
If you have been sick, you would have had medicines for sure. One of the tablets that you would have
received is a capsule. I hope you would have seen it.
Now this kind of tablet, is a bit different from the others. From the outside its just a cap, and it hides
everything that is contained within. But what lies inside may be 2 or 3 or more powders loosely arranged and packed within.
An object is something similar. It is created with the immense power of a class. while the composition of
the class could be anything (as compared to the capsule), one may not know wht is contained when you create the object handle
as in
A obj = new A();
you may say obj here is like the capsule to all those who want to consume it in their programs.
So, with this object one can use its inherent power.
Thus this concept of hiding away its true power is known as Encapsulation.
|
|