What is Encapsulation:
- Encapsulation describes the ability of an object to hide its data and methods from the rest of the world
Why is Encapsulation Needed?
Encapsulation is needed to:
- Protect data
- Control how data is used
- Prevent wrong values
- Improve security
It can be achieved using Access Modifiers:
What are Access Modifiers:
Access modifier controls where a class, method, or variable can be accessed (visibility).It decides who can use your code.
Types of Access Modifiers in Java:
- Private
- Protected
- Default
- Public
Where Can Access Modifiers Be Applied?
| Can Be Applied To | Allowed Modifiers |
| ----------------- | ----------------------------------- |
| Class | public, default |
| Method | public, private, protected, default |
| Variable | public, private, protected, default |
| Constructor | public, private, protected, default |
1. Private:
It can be accessed only inside the same class.
2. Protected:
It can be accessed inside the same class, same package, and different packages can access it using Inheritance.
3. Default(No Modifier):
It can be accessible only inside the same package.
4. Public:
It can be accessible in the same class, the same package, and from different packages, too.
Access Modifier for Class
At the class level, we can apply only public and default modifiers. Private and protected are not allowed for a class type.
public class Student// Allowed
class Student// Default class Allowed
Not Allowed
private class Student // ERROR
protected class Student // ERROR
Access Modifier for Variables:
public class Student {
public String collegeName; // accessible everywhere
private int age; // only inside class
protected int rollNo; // same package + child class(using inheritance)
String grade; // default (same package only)
}
Access Modifier for Methods:
All 4 modifier types are allowed for methods.
class Student {
public void publicMethod() { }
private void privateMethod() { }
protected void protectedMethod() { }
void defaultMethod() { }
}
| Modifier | Accessible Where? |
| --------- | -------------------------- |
| public | Everywhere |
| private | Only inside the same class |
| protected | Same package + child class+ Diff package(using inheritance)| |
| default | Same package only |
Access Modifier for Constructors:
It can have all the 4 types of modifiers.
Public Constructor:
public Student() {}//Object can be created from anywhere
Same class
Same package
Different package
Private Constructor:
private Student(int age) { }// Can only be used inside the same class
Protected Constructor:
protected Student(String name) { }//
Accessible by the same package
Different packages through inheritance
Default Constructor (No Modifier):
Student(double marks) { }
//Accessible only inside the same package.
Top comments (0)