What is encapsulation in Java?

Encapsulation in Java is a fundamental concept of object-oriented programming that helps in bundling the data (variables) and methods (functions) that operate on the data into a single unit known as a class. It restricts direct access to some of an object's components, which can prevent the accidental modification of data. In Java, encapsulation is achieved using access modifiers like private, protected, and public.

By using encapsulation, we can control the visibility of the class's data and methods, thus improving the security and maintainability of the code.

Example of Encapsulation in Java

public class Student { // Private variables private String name; private int age; // Public method to set name public void setName(String name) { this.name = name; } // Public method to get name public String getName() { return name; } // Public method to set age public void setAge(int age) { if (age > 0) { this.age = age; } } // Public method to get age public int getAge() { return age; } } public class Main { public static void main(String[] args) { Student student = new Student(); student.setName("John Doe"); student.setAge(20); System.out.println("Name: " + student.getName()); System.out.println("Age: " + student.getAge()); } }

Encapsulation Java Object-Oriented Programming Access Modifiers Class Data Hiding