Encapsulation is the process of bundling data (attributes) and operations (methods) together, with the data protected internally so that only authorized operations can modify it. Objects should encapsulate relevent data and provide corresponding behaviors.
Benefits include:
- Hiding implementation details: methods (e.g., connecting to a database) are accessed by passing parameters.
- Data validation for security and correctness.
Implementation Steps:
- Make attributes private to prevent direct modification.
- Provide public set methods to validate and assign values. public void setXxx(DataType parameterName) { // business logic for validation attribute = parameterName; }
- Provide public get methods to retrieve attribute values. public DataType getXxx() { return attribute; }
Example: package encap; public class EncapsulationExample { public static void main(String[] args) { Person person = new Person(); person.setName("John"); person.setAge(30); person.setSalary(50000); System.out.println(person.info()); Person anotherPerson = new Person("Jane", 25, 60000); System.out.println(anotherPerson.info()); } }
class Person { public String name; public int age; private double salary;
public Person() {}
public Person(String name, int age, double salary) {
setName(name);
setAge(age);
setSalary(salary);
}
public String getName() {
return name;
}
public void setName(String name) {
if (name.length() >= 2 && name.length() <= 6) {
this.name = name;
} else {
System.out.println("Invalid name length. Defaulting to null.");
this.name = null;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 1 && age <= 120) {
this.age = age;
} else {
System.out.println("Invalid age. Using default value of 18.");
this.age = 18;
}
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String info() {
return "Name: " + name + " Age: " + age + " Salary: " + salary;
}
}