What is a Setter Method?
In object-oriented programming (OOP), a setter method is a type of method that allows us to modify the value of a private or protected attribute of a class. It is also known as a “setter” or a “mutator” method. Setter methods are an essential component of encapsulation and data abstraction, which are key principles of OOP.
In the OOP paradigm, the attributes of an object are usually declared as private or protected variables. This serves the purpose of hiding the internal representation of the object from the outside world, providing a level of data protection and encapsulation. As a result, these attributes cannot be directly accessed or modified from outside the class.
To modify the values of these private or protected attributes, we use setter methods. A setter typically takes a single argument, which is the new value that we want to assign to the attribute. Inside the setter method, we can add validation or perform any additional logic before updating the attribute.
Let’s look at an example to understand the concept better. Consider a class named “Person” that has a private attribute “age” representing a person’s age. We can define a setter method called “setAge” to modify the age attribute:
“`java
public class Person {
private int age;
public void setAge(int newAge) {
if (newAge > 0) {
this.age = newAge;
} else {
System.out.println(“Invalid age!”);
}
}
}
“`
In the above example, the “setAge” method takes an integer argument “newAge” and checks if the new age is greater than 0 before assigning it to the private “age” attribute. If the new age is invalid (less than or equal to 0), we display an error message.
Using this setter method, we can update the age attribute of a Person object:
“`java
Person john = new Person();
john.setAge(30); // Valid case, age is set to 30
john.setAge(-20); // Invalid case, error message is displayed
“`
By providing a controlled interface to change attribute values, setter methods enable us to enforce restrictions, maintain data integrity, and perform necessary operations whenever an attribute is modified.
In conclusion, a setter method is an essential component of object-oriented programming. It allows us to modify the value of a private or protected attribute of a class, providing a controlled and secure way of updating data. By using setter methods, we can ensure encapsulation, data abstraction, and maintain data integrity in our programs.
Reference Articles
Read also
[Google Chrome] The definitive solution for right-click translations that no longer come up.