为什么更喜欢变量的getter和setter方法而不是公开? [英] Why to prefer getter and setter methods for variable instead of making it public?

查看:110
本文介绍了为什么更喜欢变量的getter和setter方法而不是公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么要使用getter和setter?

是的,这是一个非常简单的事情,但我没有找到一个很好的共鸣。我知道将变量设为私有并向setter提供getter以访问该变量是一个好习惯。除此之外还有什么理由吗?

Yes, It's a very simple thing but I am not finding a good reson for this. I know it is a good practice to make a variable private and providing getter to setter to access that variable. Still Is there any reason other than this ?

推荐答案

查找封装和信息隐藏。

基本上,类管理数据并为它们提供操作/提供对它们的访问,但该数据的内部表示应保持对类的私有。像这样,类可以在不破坏其他代码的情况下更改其内部表示。

Basically, a class manages data and provides operations on them/ give access to them, but the internal representation of that data should kept private to the class. Like this, a class can change its internal representation without breaking other code.

例如。考虑:

A)

    public Date date;

B)

    private Date date;


    public Date getDate(){...}
    public setDate(Date date){...}

稍后您选择使用日历而不是日期。
如果A)你不能在不破坏代码的情况下更改数据类型。

Later you choose to use Calendar instead of Date. In case A) you cannot change the data type without breaking code.

如果是B)你可以这样做:

In case B) you can do:

    private Calendar calendar;


    public Date getDate(){...}
    public setDate(Date date){...}
    public Calendar getCalendar (){...}
    public setCalendar(Calendar calendar){...}

您可以提供转换在get / setDate方法中。客户端代码不会中断。

You can provide a conversion in the get/setDate methods. Client code doesn't break.

您有时想要使用getter和setter的另一个原因是使用库/

Another reason you sometimes want to use getter and setter is the use of libraries/

基于JavaBeans模式的框架。

frameworks which base on JavaBeans patterns.

这篇关于为什么更喜欢变量的getter和setter方法而不是公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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