简体   繁体   English

为什么要使用 setter 和 getter 方法来定义某事?

[英]Why use setter and getter methods to define sth?

*Using Setter and Getter * 使用 Setter 和 Getter

class sum {
  int a;
  int b;
  int c;
  public void setSum(int a, int b) {
    c = a + b;
  } 
  public int getSum() {
    return c;
    }
  public static void main(String[] args) {
    sum s = new sum();
    s.setSum(10,7);
    System.out.println("Sum: " + s.getSum());
    }
  }

*Using just only one method (getter) *只使用一种方法(getter)

class sum1 {
  int a;
  int b;
  int c;
  public int getSum(int a, int b) {
    c = a+b;
    return c;
    }
  public static void main(String[] args) {
    sum1 s1 = new sum1();
    System.out.println("Sum: " + s1.getSum(7,10));
    }
  }

I would like to know why the teacher encouraged me to use Setter and Getter when both coding ways result the same (17)我想知道为什么老师鼓励我在两种编码方式结果相同的情况下使用Setter和Getter(17)

What specific reason lies behind using Setter and Getter?使用 Setter 和 Getter 背后的具体原因是什么?

Like visibleman said, they're not the same thing.正如visibleman所说,它们不是一回事。 They do what their names say, they set values and get values.他们按照他们的名字所说的去做,他们设定价值并获得价值。 Although you may not see the use of them in a small program.尽管您可能不会在小程序中看到它们的使用。 Their uses are noticeable in a large application where you have to modularise your code and you want to GET a value from some other class from somewhere.它们的用途在大型应用程序中很明显,在这种应用程序中,您必须模块化代码,并且希望从某个地方从其他类中获取值。 You wouldn't want that method to be 'SET'ting that value to something else while you're 'GET'ting the value.您不希望该方法在您“获取”值时“将该值设置为其他值”。 Do you understand?你明白吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM