Encapsulation is one of the four fundamental concepts (Encapsulation, Inheritance, Polymorphism, and Abstraction) in Java OOP. It is a mechanism to bundling data (variables) and code that works upon them (methods) into a single unit. By encapsulating attributes, other class cannot access them, they can only be accessed by the methods within the class. This concept helps in hiding the internal state of an object and only exposing necessary functionalities through public methods. By encapsulating data, Java ensures better data security and code maintainability.
Need for encapsulation
- Data hiding
- The internal state of an object is hidden from the outside. Direct access to the object’s data is restricted
- This can be achieved by declaring the data members of a class as
private
- Access control and validation
- Controlled access to the class data is provided through public methods (getters and setters)
- These methods allow for validation, conditional access, or transformation of data before it is set or returned.
- Improve maintainability
- Encapsulation makes the code easier to maintain and modify. Changes to the internal implementation do not affect the external code that uses the class.
Example
- Private field
- The
Person
class has two private fields:name
andage
. These fields are not accessible directly from outside the class.
- The
- Public Getters and Setters
- The class provides public methods (
getName
,setName
,getAge
,setAge
) to access and modify the private fields.
- The class provides public methods (
- Data validation
- The setter for
age
includes validation logic to ensure that the age is positive. This ensures that the internal state remains consistent and valid.
- The setter for
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaOOPEncapsulation
Reference: