发布网友 发布时间:2023-10-12 22:07
共1个回答
热心网友 时间:2024-10-26 16:28
在Java中,getter和setter是两种常规方法,用于检索和更新变量的值。(getter 检索, setter 取检索之外的变量)
public class SimpleGetterAndSetter {
private int number;
public int getNumber() {
return this.number;
}
public void setNumber(int num) {
this.number = num;
}
}
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.number = 10; // compile error, since number is private
int num = obj.number; // same
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.setNumber(10); // OK
int num = obj.getNumber(); // fine