What is Encapsulation:
Encapsulation is the process of binding data (variables) and methods into a single unit called a class. It is used to protect data from unauthorized access.
Encapsulation is achieved by:
- Declaring variables as private.
- Providing public getter and setter methods to access and update the data.
Why Use Encapsulation:
- Provides data security.
- Prevents unauthorized access.
- Improves maintainability.
- Provides better control over data.
- Follows the principle of data hiding.
class Student {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Bala");
System.out.println(s.getName());
}
}
Output:
Bala
Access Modifiers in Java
Access modifiers control the visibility and accessibility of classes, variables, methods, and constructors.
There are four types of access modifiers:
- Public
- Private
- Protected
Default
Public
A public member can be accessed from anywhere in the program
public class Demo {
public int age = 22;
}
Access:
- Same class
- Same package
- Different package
- Subclass
- Private
A private member can be accessed only within the same class.
class Demo {
private int age = 22;
}
Access:
- Same class
- Same package
- Different package
- Subclass
- Protected
A protected member can be accessed within the same package and by subclasses.
class Demo {
protected int age = 22;
}
Access:
- Same class
- Same package
- Different package
- Subclass
- Default
When no access modifier is specified, it becomes default access.
class Demo {
int age = 22;
}
Access:
- Same class
- Same package
- Different package
- Subclass (different package)
Top comments (0)