Encapsulation:
Encapsulation is one of the four core object oriented programming(OOP) principles (along with inheritance, polymorphism and abstraction).
Definition:
Encapsulation is the process of wrapping data (variables) and code (methods) into a single unit (class) and restricting directly accessing fields, we use getters and setters to control and protect data.
Uses of encapsulation:
1)Data hiding security->Sensitive data (like passwords, account balance, salary) can be kept private.
Example: In a banking system, balance is private. so users cant directly change it.
2)Controlled access->We control how variables are read or updated through getters and setters.
Example: Age should never be negative setters method can validate input.
3)Flexibility and maintainability->Internal code can be changed without affecting outside classes (loose coupling).
Example: Today you store age as int, later you can change to date of birth internally without affecting other code.
4)Improves reusability->Encapsulated classes can be reused in different applications.
Example: A student class or employee class can be reused across different projects.
5)Readability and Modularity->Code is constructed and easier to maintain, since each class handles its own data safely.
6)Better debugging->If something goes wrong, its easier to track because data modification happens only through specific methods.
Four levels of access control:
Public->The member (variable/method/class) is accessible everywhere in the project.
Used when you want to allow global access.
Private->The member is accessible only inside the same class.
Most commonly used in encapsulation (data hiding).
Outside classes cannot directly access it.
Protected->The member is accessible within the same package and in subclasses(child classes), even if they are in different packages.
Useful in inheritance.
Default->If you dont specify any modifier, it is package private.
Accessible only within the same package (not outside the package, not in subclasses).
Top comments (0)