Encapsulation
Encapsulation in very simple terms means data/information hiding. Encapsulation is a process or mechanism which binds the data and methods together and keeps them safe from outside interference, misuse and access. It is about not allowing arbitrary access to the code written in one module from other modules. The access to these codes is provided through a well defined interface.
Let’s take a real world example to understand the concept.
In a vehicle, there are several parts being used in the engine like shaft, valves, piston, heater etc. But if we see, we are not
affecting any of these components and their functionality.We are given just one interface to use them is to start the engine. In this way the internal details are kept unaffected from external impact and similarly the engine parts are not affecting anything outside.
Coming to Java, the encapsulation is achieved by a class. A class is a blue print for a real time entity defining its structure and behavior. The data defined in a class are known as member variables/instance variables and the code which operates/manipulates the data are known as member methods.
Private methods/private variables are accessed only by the same class. Public variables/methods are exposed to outside world to
access the private data.
To hide the complexity, methods and variables are
declared with the access specifiers. Typically variable are declared as private
and the methods as public.
Private: accessible within the class.
Public: accessible from anywhere.
Default: accessible within the package.
Protected: accessible from all the sub classes within
same/different packages.
Here the private member variable cannot be accessed
from outside this class, so public getter and setter methods are declared to
access from outside only through these methods.
No comments:
Post a Comment