Close

2023-08-20

What Are Getters And Setters?

What Are Getters And Setters?

Getters and setters allow you to access and modify the values of private variables in a class. They are also known as accessors and mutators, respectively. Using getters and setters, you can control how essential variables are accessed and updated in your code and prevent invalid or harmful values from being assigned.

A getter method is a method that returns the value of a private variable. It usually starts with the word “get” followed by the variable’s name, with the first letter capitalized. For example, if you have a private variable called name, you can define a getter method like this:

public String getName() {
return name;
}

A setter method is a method that sets or updates the value of a private variable. It usually starts with the word “set” followed by the variable’s name, with the first letter capitalized. It also takes a parameter of the same type as the variable and assigns it to the variable using this keyword. For example, if you have a private variable called name, you can define a setter method like this:

public void setName(String newName) {
this.name = newName;
}

Using getters and setters, you can also add validation logic to ensure that the values assigned to the private variables are valid and consistent with your design. For example, if you want to make sure that the name variable is not null or empty, you can add a check in the setter method like this:

public void setName(String newName) {
if (newName == null || newName.isEmpty()) {
throw new IllegalArgumentException(“Name cannot be null or empty”);
}
this.name = newName;
}

Getters and setters are widely used in Java and other object-oriented programming languages to implement the principle of encapsulation, which is one of the fundamental concepts of object-oriented design. Encapsulation means hiding the internal details of an object from the outside world and only exposing a public interface that defines how the object can be used. This way, you can protect your data from unauthorized or unintended access or modification and make your code more modular and maintainable.