Encapsulation in Java: Definition, Examples, and Advantages
Encapsulation in Java
Encapsulation is an object-oriented programming (OOP) concept in which an object supports data binding and data hiding to protect its internal state.
Key Concepts
Data Binding
- Data binding is the process of associating the data with an object in memory.
- It ensures that the object's data is properly managed and accessed through the object.
Data Hiding
- Data hiding is the process of restricting direct access to the object's data from other objects.
- Typically achieved by making variables private and providing getter and setter methods to access or modify the data.
Encapsulation in Practice
- If a Java object supports both data binding and data hiding, it is considered an encapsulated object.
- Encapsulation protects the integrity of the data and allows controlled access.
Example
class Student {
// Private data (data hiding)
private String name;
private int age;
// Getter method
public String getName() {
return name;
}
// Setter method
public void setName(String name) {
this.name = name;
}
// Getter method
public int getAge() {
return age;
}
// Setter method
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Arshad");
s.setAge(22);
System.out.println("Name: " + s.getName());
System.out.println("Age: " + s.getAge());
}
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Arshad");
s.setAge(22);
System.out.println("Name: " + s.getName());
System.out.println("Age: " + s.getAge());
}
}
Advantages of Encapsulation
- Protects object integrity by preventing unauthorized access
- Provides controlled access via getter/setter methods
- Makes code maintainable and flexible
- Supports data hiding and abstraction
Comments
Post a Comment