Encapsulation
In object-oriented programming, encapsulation is the process of binding data members (attributes) and methods together. Encapsulation restricts direct access to important data. A good example of the encapsulation concept is creating a class in which data members are private and methods are public, so they can be accessed through an object. In this case, only methods are allowed to access those private data.
Encapsulation in Java is an object-oriented programming concept in which the fields (variables) of a class are kept private, and access to them is provided through public methods (getters and setters). It helps protect data and control access permissions.
Create Project Name: Encapsulation
Source Code: Student.java
public class Student {
// Step 1: Private fields
private String name;
private int age;
private String studentId;
// Step 2: Public getter and setter methods for each field
public String getName() {
return name;
}
public void setName(String name) {
// You can add validation here
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
// Example of simple validation
if (age > 0) {
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
}
Source Code: Encapsulation.java
public class Encapsulation {
public static void main(String[] args) {
Student student = new Student();
// Using setters to set data
student.setName("Alice");
student.setAge(20);
student.setStudentId("S12345");
// Using getters to access data
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());
System.out.println("Student ID: " + student.getStudentId());
}
}
Result:
Advantages of Java OOPs
Below are the advantages of using OOPs in Java:
- The implementation of OOPs concepts is easier.
- The execution of OOPs is faster than procedural-oriented programming.
- OOPs provides code reusability, so programmers can reuse existing code.
- OOPs helps us in hiding important data.

