使用getter和setter(只获取和设置)而不是简单地为这些变量使用公共字段有什么好处?

如果getter和setter所做的不仅仅是简单的get/set,我可以很快地解决这个问题,但我不是100%清楚如何做到:

public String foo;

比:

private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }

而前者需要的样板代码要少得多。


当前回答

原因有很多。我最喜欢的是当你需要改变行为或调整你可以设置的变量时。例如,假设您有一个setSpeed(intspeed)方法。但你希望你只能将最大速度设置为100。您可以执行以下操作:

public void setSpeed(int speed) {
  if ( speed > 100 ) {
    this.speed = 100;
  } else {
    this.speed = speed;
  }
}

现在,如果代码中的每个地方都使用公共字段,然后意识到需要上述要求,该怎么办?寻找公共领域的每一种用法,而不仅仅是修改你的setter。

我的2美分:)

其他回答

OO设计的基本原则之一:封装!

它给您带来了许多好处,其中之一是您可以在幕后更改getter/setter的实现,但只要数据类型保持不变,任何具有该值的使用者都将继续工作。

编辑:我回答这个问题是因为有很多学习编程的人都在问这个问题,大多数答案在技术上都很好,但如果你是新手,就不那么容易理解了。我们都是新手,所以我想我会尝试一个更适合新手的答案。

两个主要的是多态性和验证。即使它只是一个愚蠢的数据结构。

假设我们有一个简单的类:

public class Bottle {
  public int amountOfWaterMl;
  public int capacityMl;
}

这是一个非常简单的类,它包含有多少液体,容量是多少(毫升)。

当我这样做时会发生什么:

Bottle bot = new Bottle();
bot.amountOfWaterMl = 1500;
bot.capacityMl = 1000;

嗯,你不会指望这会奏效,对吧?你想进行某种理智检查。更糟糕的是,如果我从未指定最大容量呢?哦,亲爱的,我们有问题。

但也有另一个问题。如果瓶子只是一种容器呢?如果我们有几个容器,所有容器都有容量和液体量,会怎么样?如果我们能做一个接口,我们就可以让程序的其他部分接受这个接口,而瓶子、偷工减料和各种各样的东西就可以互换使用了。那不是更好吗?由于接口需要方法,这也是一件好事。

我们最终会得到这样的结果:

public interface LiquidContainer {
  public int getAmountMl();
  public void setAmountMl(int amountMl);
  public int getCapacityMl();
}

太棒了现在我们把瓶子换成这个:

public class Bottle extends LiquidContainer {
  private int capacityMl;
  private int amountFilledMl;

  public Bottle(int capacityMl, int amountFilledMl) {
    this.capacityMl = capacityMl;
    this.amountFilledMl = amountFilledMl;
    checkNotOverFlow();
  }

  public int getAmountMl() {
    return amountFilledMl;
  }

  public void setAmountMl(int amountMl) {
     this.amountFilled = amountMl;
     checkNotOverFlow();
  }
  public int getCapacityMl() {
    return capacityMl;
  }

  private void checkNotOverFlow() {
    if(amountOfWaterMl > capacityMl) {
      throw new BottleOverflowException();
    }
}

我将把BottleOverflowException的定义作为练习留给读者。

现在请注意这是多么的强大。我们现在可以通过接受LiquidContainer而不是Bottle来处理代码中的任何类型的容器。这些瓶子是如何处理这种东西的呢。您可以有在磁盘发生变化时将其状态写入磁盘的瓶子,也可以有保存在SQL数据库或GNU知道其他内容的瓶子。

所有这些都可以有不同的方法来处理各种各样的百日咳。瓶子只是检查,如果它溢出,就会抛出RuntimeException。但这可能是错误的做法。(关于错误处理有一个很有用的讨论,但我有意保持非常简单。评论中的人可能会指出这种简单方法的缺点。;)

是的,我们似乎从一个非常简单的想法迅速得到更好的答案。

请注意,您不能更改瓶子的容量。它现在被镶嵌在石头上。您可以通过将int声明为final来实现这一点。但如果这是一个列表,你可以清空它,添加新的东西,等等。你不能限制接触内脏的权限。

还有第三件事不是每个人都解决过:getter和setter使用方法调用。这意味着它们看起来像其他地方的正常方法。DTO和其他东西没有奇怪的特定语法,而是到处都有相同的语法。

我只是想补充一点,即使有时它们对于变量/对象的封装和安全是必要的,如果我们想编写一个真正的面向对象的程序,那么我们需要停止过度使用附件,因为有时我们在不真正必要的情况下非常依赖它们,这几乎与我们将变量公开一样。

我花了很长时间来思考Java案例,我相信真正的原因是:

接口的代码,而不是实现接口只指定方法,不指定字段

换句话说,在接口中指定字段的唯一方法是提供一个用于写入新值的方法和一个用于读取当前值的方法。

这些方法是臭名昭著的getter和setter。。。。

如果您想要一个只读变量,但不想让客户端改变访问它的方式,请尝试使用这个模板类:

template<typename MemberOfWhichClass, typename primative>                                       
class ReadOnly {
    friend MemberOfWhichClass;
public:
    template<typename number> inline bool   operator==(const number& y) const { return x == y; } 
    template<typename number> inline number operator+ (const number& y) const { return x + y; } 
    template<typename number> inline number operator- (const number& y) const { return x - y; } 
    template<typename number> inline number operator* (const number& y) const { return x * y; }  
    template<typename number> inline number operator/ (const number& y) const { return x / y; } 
    template<typename number> inline number operator<<(const number& y) const { return x << y; }
    template<typename number> inline number operator^(const number& y) const  { return x^y; }
    template<typename number> inline number operator~() const                 { return ~x; }
    template<typename number> inline operator number() const                  { return x; }
protected:
    template<typename number> inline number operator= (const number& y) { return x = y; }       
    template<typename number> inline number operator+=(const number& y) { return x += y; }      
    template<typename number> inline number operator-=(const number& y) { return x -= y; }      
    template<typename number> inline number operator*=(const number& y) { return x *= y; }      
    template<typename number> inline number operator/=(const number& y) { return x /= y; }      
    primative x;                                                                                
};      

示例用途:

class Foo {
public:
    ReadOnly<Foo, int> cantChangeMe;
};

记住,您还需要添加按位和一元运算符!这只是为了让你开始