set 和 get 方法与公共变量的优势 [英] Advantage of set and get methods vs public variable

查看:37
本文介绍了set 和 get 方法与公共变量的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么要使用 getter 和 setter?

在类中创建访问私有变量的方法而不是将变量设为公开有什么好处吗?

Is there any advantage to making methods to access private variables in your class instead of making the variable public?

例如第二种情况是否比第一种情况好?

For example is the second case better than the first?

//Case 1
public class Shoe{
    public int size;
}

//Case 2
public class Shoe{
    private int size;
    public int getSize(){
        return size;
    }

    public void setSize(int sz){
        size = sz;
    }

}

推荐答案

我有一天在 SO 上看到的,作为答案(由@ChssPly76 编写)为什么要使用 getter 和 setter

What I have seen someday on SO, as answer (written by @ChssPly76) why to use getters and setters

因为从现在起 2 周(几个月、几年),当您意识到您的setter 需要做的不仅仅是设置值,你还会意识到该属性已直接用于 238 个其他类:-)

Because 2 weeks (months, years) from now when you realize that your setter needs to do more than just set the value, you'll also realize that the property has been used directly in 238 other classes :-)

还有更多优点:

  1. getter 和 setter 可以在其中进行验证,字段不能
  2. 使用 getter,您可以获取所需类的子类.
  3. getter 和 setter 是多态的,字段不是
  4. 调试可以简单得多,因为断点可以放置在一个方法内,而不是靠近给定字段的许多引用.
  5. 他们可以隐藏实施更改:
  1. getters and setter can have validation in them, fields can't
  2. using getter you can get subclass of wanted class.
  3. getters and setters are polymorphic, fields aren't
  4. debugging can be much simpler, because breakpoint can be placed inside one method not near many references of that given field.
  5. they can hide implementation changes:

之前:

private boolean alive = true;

public boolean isAlive() { return alive; }
public void setAlive(boolean alive) { this.alive = alive; }

之后:

private int hp; // change!

public boolean isAlive() { return hp > 0; } // old signature 
 //method looks the same, no change in client code
public void setAlive(boolean alive) { this.hp = alive ? 100 : 0; }

编辑:使用 Eclipse 时的另一个新优势 - 您可以在字段上创建观察点,但如果您有设置器,则只需要一个断点,并且... 断点(例如在 setter 方法中)可以是有条件的,观察点(在字段上)不能.因此,如果您只想在 x=10 时停止调试器,则只能使用 setter 中的断点来完成.

EDIT: one additional new advange when you are using Eclipse - you can create watchpoint on field, but if you have setter you need just a breakpoint, and... breakpoints (e.g. in setter method) can be conditional, watchpoints (on field) cannot. So if you want to stop your debugger only if x=10 you can do it only with breakpoint inside setter.

这篇关于set 和 get 方法与公共变量的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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