Java Encapsulation Interview Questions
Java Encapsulation Interview Questions
Encapsulation is the process of wrapping data (fields) and methods into a single unit. In Java,
encapsulation is achieved by declaring class variables as private and providing public getter and
2. Providing public getter and setter methods to access and update the private fields.
Example:
class Student {
return name;
}
public void setName(String name) {
this.name = name;
Encapsulation allows changes to the implementation of a class without affecting the classes that use
it. By using getter and setter methods, you can modify the internal logic without changing the
external interface.
- Encapsulation focuses on binding data and methods together and controlling access to data.
- Abstraction focuses on hiding implementation details and showing only the functionality to the
user.
Example:
class Employee {
return empId;
this.empId = empId;
}
return empName;
this.empName = empName;
class Main {
emp.setEmpId(101);
emp.setEmpName("John Doe");