Getters and setters are methods that provide controlled access to the fields of a class in Java. They are a fundamental part of encapsulation, one of the core principles of object-oriented programming (OOP).
Reasons for Using Getters and Setters:
- Encapsulation:
- Encapsulation is one of the core principles of object-oriented programming (OOP). By making fields private and providing public getters and setters, you can control how the data is accessed and modified.
- It hides the internal implementation details and protects the integrity of the object's data.
- Data Validation:
- Setters can be used to enforce constraints or validation before assigning a value to a private variable. For example, you can prevent a negative value from being assigned to a variable that should always be positive.
- Example:
```java
public class Person {
private int age;
public void setAge(int age) { if (age > 0) { this.age = age; } else { throw new IllegalArgumentException("Age must be positive"); } } public int getAge() {
return age;
}
}
```
7. Controlled Access:
8. Getters and setters allow you to control access to the fields. For example, you can make a field read-only by providing only a getter method without a setter.
9. This allows the class to be immutable or partially immutable.
10. Maintaining Compatibility:
11. If you initially make fields public and later decide to change the internal representation or add validation, it can break the existing code that directly accesses those fields.
12. Using getters and setters from the beginning allows you to change the implementation details later without affecting the external code that uses your class.
Example of Using Getters and Setters with Private Variables:
public class Employee { private String name; private double salary;
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for salary
public double getSalary() {
return salary;
}
// Setter for salary
public void setSalary(double salary) {
if (salary > 0) {
this.salary = salary;
} else {
throw new IllegalArgumentException("Salary must be positive");
}
}
}
Benefits of Making Variables Private and Using Getters/Setters:
- Encapsulation and Data Integrity:
- By making the variables private, you protect the internal state of the object from being directly manipulated from outside the class. This helps maintain the integrity of the object's data.
- Flexibility:
- Getters and setters allow you to change the internal implementation without affecting the external code that depends on your class. For example, if you later decide to store the salary in a different format (e.g., in cents rather than dollars), you can adjust the setter and getter without changing the public interface.
- Security:
- By controlling access to the data, you can enforce security constraints and ensure that only authorized code can modify the internal state of the object.