java中getter
Getters and setters are used to protect your data, particularly when creating classes.
Getter和Setter用于保护数据,尤其是在创建类时。
For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
对于每个实例变量,getter方法将返回其值,而setter方法将设置或更新其值。 鉴于此,getter和setter也分别称为存取 器和更改器 。
By convention, getters start with the word "get" and setters with the word "set", followed by a variable name. In both cases the first letter of the variable's name is capitalized:
按照惯例,getter以单词“ get”开头,setter以单词“ set”开头,后跟一个变量名。 在这两种情况下,变量名称的首字母均大写:
public class Vehicle {
private String color;
// Getter
public String getColor() {
return color;
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute.
getter方法返回属性的值。 setter方法采用参数并将其分配给属性。
Once the getter and setter have been defined, we use it in our main:
一旦定义了getter和setter,就可以在主要代码中使用它:
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
v1.setColor("Red");
System.out.println(v1.getColor());
}
// Outputs "Red"
Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.
使用getter和setter可以控制值。 您可以在实际设置值之前在设置器中验证给定值。
为什么要使用getter和setter? (Why use getters and setters?)
Getters and setters allow you to control how important variables are accessed and updated in your code. For example, consider this setter method:
使用Getter和Setter可以控制如何在代码中访问和更新重要的变量。 例如,考虑以下setter方法:
public void setNumber(int number) {
if (number < 1 || number > 10) {
throw new IllegalArgumentException();
}
this.number = num;
}
By using the setNumber
method, you can be sure the value of number
is always between 1 and 10. This is much better than updating the number
variable directly:
通过使用setNumber
方法,可以确保number
的值始终在1到10之间。这比直接更新number
变量要好得多:
obj.number = 13;
If you update number
directly, it's possible that you'll cause unintended side effects somewhere else in your code. Here, setting number
to 13 violates the 1 to 10 constraint we want to establish.
如果直接更新number
,则可能会在代码的其他地方引起意外的副作用。 在这里,将number
设置为13违反了我们要建立的1到10约束。
Making number
a private variable and using the setNumber
method would prevent this from happening.
将number
setNumber
私有变量并使用setNumber
方法可以防止这种情况的发生。
On the other hand, the only way to read the value of number
is by using a getter method:
另一方面,读取number
值的唯一方法是使用getter方法:
public int getNumber() {
return this.number;
}
翻译自: https://www.freecodecamp.org/news/java-getters-and-setters/
java中getter