我只是想知道使用 set 和 get 方法与仅使用 object.variableName 来设置和获取是否有什么区别?谢谢。
package hello;
public class Helloworld {
int num;
public static void main(String[] args) {
Helloworld hello1 = new Helloworld();
Helloworld hello2 = new Helloworld();
hello1.num = 5;
System.out.println(hello1.num);
hello2.setNum(5);
System.out.println(hello2.getNum());
}
void setNum(int i) {
this.num = i;
}
int getNum() {
return this.num;
}
}
最佳答案
主要原因是封装。您希望变量是私有(private)的,并且不能由用户或客户端直接修改,因为它可能会影响系统其他部分的行为。
关于java - 当你可以只使用 object.variable 名称来获取或设置时,为什么还要使用 set 和 get 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29500771/