Introduction
- Encapsulation is one of the four core principles of Object-Oriented Programming (OOPS) in Java.
- It focuses on data security and controlled access by binding data (variables) and methods into a single unit called a class. Encapsulation means wrapping data and methods together and hiding sensitive data from outside access.
- In Java, encapsulation is achieved by:
- Declaring variables as private
- Providing public getter and setter methods
In simple words:
Encapsulation = Data hiding + Controlled access
Why Encapsulation is Important?
- Protects data from unauthorized access
- Improves code security
- Makes code easier to maintain
- Allows validation before data modification
- Enhances flexibility
Steps to Achieve Encapsulation
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
1. Private:
It can be accessed only inside the same class.
Example:
class Student {
private int age; // private variable
private void showAge() {
System.out.println("Age: " + age);
}
public void setAge(int age) {
this.age = age;
showAge();
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setAge(20);
}
}
2. Protected:
It can be accessed inside the same class, same package, and different packages can access it using Inheritance.
Example 1:
class Parent {
protected void display() {
System.out.println("Protected method");
}
}
class Child extends Parent {
void show() {
display(); // accessible due to inheritance
}
}
Example 2:
public class Parent {
protected void msg() {
System.out.println("Hello from Parent");
}
}
public class Child extends Parent {
public static void main(String[] args) {
Child c = new Child();
c.msg(); // accessible using inheritance
}
}
3. Default(No Modifier):
It can be accessible only inside the same package.
Example:
class Employee {
int empId;
void showId() {
System.out.println(empId);
}
}
class Test {
public static void main(String[] args) {
Employee e = new Employee();
e.empId = 101;
e.showId();
}
}
4. Public:
It can be accessible in the same class, the same package, and from different
Example:
public class College {
public String name = "ABC College";
public void display() {
System.out.println("College Name: " + name);
}
}
public class Test {
public static void main(String[] args) {
College c = new College();
c.display(); // accessible everywhere
}
}
Top comments (0)