Encapsulation in Java is the inclusion of all methods and variables needed for a Java object to function, contained within the object itself. Encapsulation, along with abstraction, polymorphism and inheritance, is one of the four key concepts in object oriented programming (OOP). Encapsulation is similar across object-oriented languages.
In OOP, objects are the first things a programmer considers when designing a program. They are also the units of code that are eventually derived from the process and what actually runs in the computer system. Each object is an instance of a particular class or subclass with the class's own methods and variables.
Java offers four different "scope" realms--public, protected, private, and package--that can be used to selectively hide data constructs. To achieve encapsulation, the programmer declares the class variables as “private” and then provides what are called public “setter and getter” methods which make it possible to view and modify the variables. A Java object publishes its interfaces, which consist of public methods and instantiated data, enabling other objects to interact with it without the object’s inner workings being revealed. Data hiding ensures that someone maintaining the code can’t inadvertently point to or access the wrong data. Programmers creating objects to interact with existing objects need not know how the encapsulated code works specifically, just how to use its interface.
Java object encapsulation enables the reuse of code that has already been tested. The inherent modularity of objects means that their source code can be written and maintained independently from the source code for other objects and makes them portable within a system. Furthermore, if there is a problem with a given object, it can be removed and replaced without affecting the rest of the program.
See a tutorial on encapsulation in Java: