Expanded upon "why getter and setter?" (#21417)
* Expanded upon "why getter and setter?" * Fixed formatting issues and typo
This commit is contained in:
@ -5,7 +5,7 @@ title: Getters & Setters
|
||||
# Getters & Setters
|
||||
Getters and Setters are used to effectively protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Getters and setters are also known as accessors and mutators, respectively.
|
||||
|
||||
By convention, getters start with get, followed by the variable name, with the first letter of the variable name capitalized. Setters start with set, followed by the variable name, with the first letter of the variable name capitalized.
|
||||
By convention, getters start with `get`, followed by the variable name, with the first letter of the variable name capitalized. Setters start with `set`, followed by the variable name, with the first letter of the variable name capitalized.
|
||||
|
||||
***Example:***
|
||||
```java
|
||||
@ -42,7 +42,7 @@ Getters and setters allow control over the values. You may validate the given v
|
||||
|
||||
## Why getter and setter?
|
||||
|
||||
By using getter and setter, the programmer can control how their important variables are accessed and updated, such as changing value of a variable within a specified range. Consider the following code of a setter method:
|
||||
By using getter and setter, the programmer can control how important variables are accessed and updated, such as changing value of a variable within a specified range. Consider the following code of a setter method:
|
||||
```java
|
||||
public void setNumber(int num) {
|
||||
if (num < 10 || num > 100) {
|
||||
@ -51,7 +51,7 @@ public void setNumber(int num) {
|
||||
this.number = num;
|
||||
}
|
||||
```
|
||||
This ensures the value of number is always set between 10 and 100. If the programmer allows the variable number to be updated directly, the caller can set any arbitrary value to it:
|
||||
This ensures the value of `number` is always set between 10 and 100. If the programmer allows the variable number to be updated directly, the caller can set any arbitrary value to it:
|
||||
```java
|
||||
obj.number = 3;
|
||||
```
|
||||
@ -63,3 +63,4 @@ public int getNumber() {
|
||||
return this.number;
|
||||
}
|
||||
```
|
||||
Getters and setters are so widely used that some some Integrated Development Environments (IDEs) allow these methods to be generated automatically. They also prevent the possible need of making fields public, which can cause unforeseen issues when the caller alters these fields.
|
||||
|
Reference in New Issue
Block a user