encapsulation in Java

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 Software development best practices and processes

App Architecture
Software Quality
  • How to test a predictive model

    Strategies for testing predictive models and analytics emphasize data quality, real-time testing and code redundancy, as well as ...

  • The dos and don'ts of visual testing

    The visual aspect of an application is an important part of UX. Defects can potentially result in lost sales and damaged ...

  • 3 QA testing tools to consider

    QA testers need to be able to put applications and APIs through their paces. Here are some examples of tools that can help with ...

Cloud Computing