Definition

encapsulation in Java

Contributor(s): Matthew Haughn

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:

This was last updated in July 2016

Continue Reading About encapsulation in Java

Dig Deeper on Mobile development and deployment

PRO+

Content

Find more PRO+ content and other member only offers, here.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

File Extensions and File Formats

SearchCloudApplications

SearchSoftwareQuality

SearchFinancialApplications

SearchSAP

SearchManufacturingERP

Close