DEV Community

nantha kumar
nantha kumar

Posted on

Encapsulation

What is encapsulation :

  1. Encapsulation is data protection.

Why used encapsulation :

  1. Encapsulation provides data security, better control.

Benefits of Encapsulation :

  1. Data Hiding → Sensitive data is not directly accessible.
  2. Control over Data → You can validate values before setting them.
  3. Improves Security → External code can’t directly change internal variables.

How to protect the data :

  1. Using access modifier.

What is access modifier :

  1. An access modifier in Java defines who can access a class, variable, method, or constructor.

Real time example :

Access Modifier Within Class Same Package Subclass (other package) Outside Package
private ✅ Yes ❌ No ❌ No ❌ No
default (no keyword) ✅ Yes ✅ Yes ❌ No ❌ No
protected ✅ Yes ✅ Yes ✅ Yes ❌ No
public ✅ Yes ✅ Yes ✅ Yes ✅ Yes

Top comments (0)