ENCAPSULATION IN JAVA - ASSIGNMENT
What is Encapsulation?
Encapsulation is an Object-Oriented Programming
concept where data (variables) and methods are
combined into a single unit called a class. It protects the
data by making variables private and providing public
getter and setter methods to access them. This
improves security, control, and maintainability of the
program.
How to Implement Encapsulation?
1. Declare variables as private
2. Provide public getter and setter methods
3. Access data only through these methods
Create Employee Class (Encapsulation Example)
class Employee {
private int id;
private String name;
private int age;
private double salary;
private String dept;
public Employee(int id, String name, int age, double salary, String dept) {
[Link] = id;
[Link] = name;
[Link] = age;
[Link] = salary;
[Link] = dept;
}
public int getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
public double getSalary() { return salary; }
public String getDept() { return dept; }
public void setSalary(double salary) {
[Link] = salary;
}
}
Store Employees in Array and Process Salaries
public class Main {
public static void main(String[] args) {
Employee[] emp = new Employee[3];
emp[0] = new Employee(1, "Shalin", 22, 25000, "IT");
emp[1] = new Employee(2, "Arun", 25, 30000, "HR");
emp[2] = new Employee(3, "Kiran", 24, 28000, "Finance");
double total = 0;
for(Employee e : emp) {
total += [Link]();
}
double avg = total / [Link];
[Link]("Average Salary: " + avg);
for(Employee e : emp) {
if([Link]() > avg) {
double newSalary = [Link]() + 2000; // hike
[Link](newSalary);
}
}
for(Employee e : emp) {
[Link]([Link]() + " " + [Link]() + " " + [Link]());
}
}
}
Conclusion
Encapsulation protects data and provides controlled
access through methods. It improves data security and
makes the program more reliable and easy to maintain.
Using arrays and loops, we can manage multiple
employee objects efficiently.