Remember, an object is a self-contained thing that contains data elements and actions it can perform on those data elements. This is an implementation of a principle known as information hiding. The idea is that an object knows about itself. If another object wants facts about the first object, it has to ask. In OOP terms, it has to send the object a message to ask for its age. In Java terms, it has to call a method on the object that will return the age. Encapsulation ensures that each object is distinct, and that programs are conversations among objects. The Java language lets a programmer violate this principle, but it's almost always a bad idea to do so.
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;
}
}
Here's an encapsulation starter rule of thumb:
-> Mark instance variables private.
-> Mark getters and setters public.
0 comments:
Post a Comment