吸气剂和制定者有什么意义? [英] What is the point of getters and setters?

查看:184
本文介绍了吸气剂和制定者有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么要使用getter和setter?

我看过书在 Java 上,说可以为变量创建setter和getters,例如 x ÿ。例如:

I have read books on Java, saying that it is good to create setters and getters for variables such as x and y. For example:

public int getX(){
    return x;
}

public void setX(int x){
    this.x = x;
}

但与此有什么不同

...(shape.x)...   // basically getX()

shape.x = 90;    // basically setX()

如果setter和getter更好,你能解释一下实际问题吗会出现吗?

If setters and getters are better, could you explain to me what practical problems would arise?

推荐答案

多个原因:


  • 如果您允许字段访问,例​​如

  • If you allow field access like

shape.x = 90

shape.x = 90

然后你不能在将来添加任何逻辑来验证数据。

then you cannot add any logic in future to validate the data.

如果x不能小于100你不能这样做,但是如果你有像

say if x cannot be less than 100 you cannot do it, however if you had setters like

public void setShapeValue(int shapeValue){
  if(shapeValue < 100){
    //do something here like throw exception.
  }
}




  • 你不能添加一些东西喜欢写入逻辑上的副本(参见 CopyOnWriteArrayList

  • 另一个原因是为了访问班级以外的字段,您必须将它们标记为公共,受保护或默认,因此您将失去控制权。当数据非常类似于打破封装并且一般< a href =http://en.wikipedia.org/wiki/Object-oriented_programming =noreferrer> OOPS 方法。

    • You cannot add something like copy on write logic (see CopyOnWriteArrayList)
    • Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.
    • 虽然对于常量如

      public final String SOMETHING = "SOMETHING";
      

      您将允许字段访问,因为它们无法更改,例如您将使用getter放置它们的变量, setter。

      you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.


      • 另一种情况是你希望你的类是不可变的,如果你允许字段访问,那么你就会破坏你的类的不变性因为价值可以改变。但是,如果你仔细设计你的课程与吸气剂和没有安装者,你保持不变性不变。

      虽然在这种情况下你必须小心getter方法,以确保你不提供对象的引用(如果你的class将对象作为实例)。

      Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).

      我们可以使用getter和setter在任何包中使用私有变量。

      We can use the private variables in any package using getters and setters.

      这篇关于吸气剂和制定者有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆