Java Exercise
In this exercise, you will create a Java program that defines a class named Employee
with private attributes such as name
, age
, and salary
. You will use access modifiers to protect these attributes and provide access through public getters
and setters
methods. The objective is to show how encapsulation allows you to control access and modification of a class's data, ensuring the object's integrity.
Instructions:
- Create a class named
Employee
with private attributes name
, age
, and salary
.
- Define
getters
and setters
methods to access and modify attribute values.
- In the main method, create an object of the
Employee
class, use the setters
methods to assign values, and then display the data using the getters
methods.
This exercise will help you understand how to use encapsulation to protect data within a class and expose it in a controlled manner, a fundamental principle in programming. object-oriented.
View Example Code
public class Employee {
// Private attributes
private String name;
private int age;
private double salary;
// Constructor to initialize the attributes
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
// Getter and Setter for the 'name' attribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter for the 'age' attribute
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Getter and Setter for the 'salary' attribute
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public static void main(String[] args) {
// Create an Employee object
Employee employee1 = new Employee("Juan Pérez", 30, 2500.00);
// Use getters to display employee details
System.out.println("Name: " + employee1.getName());
System.out.println("Age: " + employee1.getAge());
System.out.println("Salary: " + employee1.getSalary());
// Modify attributes using setters
employee1.setSalary(3000.00);
System.out.println("\nUpdated salary: " + employee1.getSalary());
}
}
Output:
Name: Juan Pérez
Age: 30
Salary: 2500.00
Updated Salary: 3000.00
This program shows how **Encapsulation** in Java allows you to control access to a class's data using getters
and setters
methods, thus ensuring data integrity and security.