Java:为什么要get和set方法

在JavaBean中,通常将属性设置为private,然后生成与属性对应的public setXXX(),public getXXX()。那么为什么要这么设计呢?

同一个类 同一个包 同一个包下的子类 不同包下的子类 不同包的非子类
public + + + +
protected + + +
private +

根据上表可以得知,将属性设置为private限制了外界对这个属性的直接访问操作,那么设置对应的get、set方法并设为public的意义就相当于给外界提供了访问的方法,而不是直接将属性暴露。

引用Stackoverflow的答案:

  • Encapsulation of behavior associated with getting or setting the property this allows additional functionality (like validation) to be added more easily later.
  • Hiding the internal representation of the property while exposing a property using an alternative representation.
  • Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
  • Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
  • Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
  • Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.
  • Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
  • Allowing the getter/setter to be passed around as lambda expressions rather than values.
  • Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.

自己目前所理解的:

  • 实现java域变量的封装性和安全性
  • 可以对属性进行验证操作,比如age属性,在set中可以添加验证,如果输入的age小于0则抛出异常
  • 可以在debug的时候用到