Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当您可以使用object.variable name获取或设置时,为什么要使用set和get方法?_Java_Object_Methods_Get_Set - Fatal编程技术网

Java 当您可以使用object.variable name获取或设置时,为什么要使用set和get方法?

Java 当您可以使用object.variable name获取或设置时,为什么要使用set和get方法?,java,object,methods,get,set,Java,Object,Methods,Get,Set,我只是想知道使用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.n

我只是想知道使用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;

}
}

因为有时候,变量是私有的,不能通过
obj.varname
访问。简而言之:封装


为了保护您的程序,您希望变量尽可能多地是私有的,有时如果您想检查它是否是有效值或类似的值,set方法会更好。

主要原因是封装。您希望您的变量是私有的,用户或客户端不能直接修改,因为它可能会影响系统其他部分的行为。

这基本上是与封装概念有关的最佳实践

如果您使用get和set方法,那么在以后决定向get或set方法添加一些额外的逻辑(例如验证)时,您将具有更大的灵活性


对于getter,如果变量是原语,您还可以阻止using类修改该变量。

此外,您以后可能还需要为变量添加限制,该限制可以在设置数字时进行检查。将变量设为私有,以便它们只能在同一类中访问,这难道不是一个想法吗?如果getter和setter方法可以访问这些私有变量,那么为什么要使它们私有呢?谢谢。@skillet getter和setter可以提供对所述变量的有限访问,和/或根据您希望用户看到的内容提供输出。我认为这已经得到了多次回答。这是以前回答过的这个问题的例子之一。