8

getter和setter

 3 years ago
source link: http://www.cnblogs.com/wxlmdx/p/12950557.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

getter 和setter

  • 子类中为什么要写get和set方法获取释放数据,不写会怎样?在什么情况下要用getter和setter? getter通常与一个私有的实例变量对应,用于返回该变量的值

    public int getXxxx()
    {
        return "相应的实例变量";
    }

setter通常与一个私有的实例变量对应,用于设置该变量的值

  public void setXxxx(类型参数)
  {
      实例变量=参数;
  }

其中 setXxx的参数类型通常要跟相应的实例变量类型相同。

通常,将实例变量私有化,并为其提供相应的getter和setter。

将实例变量私有化是为了隐藏类的实现细节,不对外暴露。

如果期望外部还能访问私有的实例变量,可以为其提供相应的getter和setter。

如果不期望外部能访问私有变量,则不需要提供相应的getter和setter。

如果父类中存在私有的实例变量,期望子类能够访问,则父类需要为这些实例变量提供相应的getter和setter。

  • 如果成员变量是public修饰,还需要get和set方法吗? 不需要要,因为可以直接访问。

  • 那为什么非要将成员变量私有化再提供getter和setter?

    private intage;//字段(field)
    public int getNianLing()
    {
        return age;
    }

    getNianLing()->去掉get和参数部分->NianLing NianLing->将首字母变小写->nianLing 这里得到的 nianLing 就是属性 (property)

    private int x;//字段(field)
    public int getAge()
    {//实例变量x对应的getter
        returnx;
    }

    getAge()->去掉get和参数部分->Age->将首字母变小写->age 这里得到的age就是属性 (property) ,它与x字段对应


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK