Why to prefer getter and setter methods for variab

2019-05-28 22:49发布

Possible Duplicate:
Why use getters and setters?

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 ?

标签: java oop
4条回答
爷、活的狠高调
2楼-- · 2019-05-28 23:19

Lookup "encapsulation" and "information hiding".

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.

E.g. consider:

A)

    public Date date;

B)

    private Date date;


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

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

In case B) you can do:

    private Calendar calendar;


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

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

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

frameworks which base on JavaBeans patterns.

查看更多
Emotional °昔
3楼-- · 2019-05-28 23:24

If you leave variable public, you can't make sure the object will keep consistent state. In your setters you can for example have some checking like e.g. avoid setting negative number as age.

If you have public variable you drop for example possibility of having listeners since listeners are typically using notifications on setting the variable via setter. There is no chance to track the change when directly changing public variable.

These are some very basic examples but can be found more for sure.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-05-28 23:35
  • Only provide getters/setters if it is actually needed, don't just do it automatically
  • A getter/setter hides the internal implementation and in theory gives you a well defined interface and allows you to change the internal implementation without clients having to change their code
查看更多
对你真心纯属浪费
5楼-- · 2019-05-28 23:38

There are many reasons. It is a way to control access(accessors) to the inner workings of your class. Sometimes for example you may want the getter to return a clone of the object or the setter to just copy values on the private object rather than pointing the handler to the new object passed to the setter. Another reason would be to do something before or after you get or set an object without exposing this functionality.

To sum it up:

  1. You give room for future extensions
  2. You close the door to uncontrolled access

Use them only if needed though.

查看更多
登录 后发表回答