DEV Community

Praveen Kumar K
Praveen Kumar K

Posted on

What is Encapsulation in OOP's Concepts?

Encapsulation in Java:

Encapsulation in Java is an object-oriented principle that binds data and methods into a single unit, typically a class. It restricts direct access to data by hiding implementation details. This ensures controlled interaction with the data through defined methods.

•Achieved using access modifiers like private, protected, and public.

•Improves data security by allowing validation through getters and setters.

•Enhances code maintainability by isolating changes within the class.

How Encapsulation is Achieved in Java?

•Private data members.

•Public getter and setter methods.

Key Rules:

Declare data as private:

•Hide the class data so it cannot be accessed directly from outside the class.

Use getters and setters:

•Keep variables private and provide public getter and setter methods for controlled access and safe modification, often with validation.

Apply proper access modifiers:

•Use private for data hiding and public for methods that provide access.

Program:

Ref(geeksforgeeks.org)

Top comments (0)