Purpose of getters and setters? [duplicate]

2019-08-05 21:56发布

Possible Duplicates:
Public Data members vs Getters, Setters
Purpose of private members in a class

What is the use of getters and setters when you can just make your variables public and avoid the hassle of such lines as A.setVariableX(A.getVariableY())?

5条回答
啃猪蹄的小仙女
2楼-- · 2019-08-05 22:04

Because sometimes there are some constraints as to what your variable might be and having to check that when you set it make sense.

for instance, if your Age is not allowed to be -1, you would check that in your setter.

if(value >= 0)
{
   _age = value;
}
else
{
  throw new InvalidAgeException("Age may not be less than 0");
}
查看更多
Bombasti
3楼-- · 2019-08-05 22:05

Setters and getters apply to properties, whatever "properties" are in your code.

For instance, you can have an angle variable, which stores an angle value expressed in radians. you can then define setters and getters for this variable, with any angle unit that you think relevant.

查看更多
迷人小祖宗
4楼-- · 2019-08-05 22:18

Getters and setters can do validation, and lazy instantiation, whereas public members cannot.

As an aside, this isn't language agnostic, as most of the languages that implement properties abstract away the implementation so they look like public members in code.

查看更多
倾城 Initia
5楼-- · 2019-08-05 22:24

To hide implementation details. If you choose to make your properties public instead, then later decide to change the way they work, you have to change all of the associated code.

With getters and setters, you can often change the internal implementation details without changing the visible API (and thus avoid having to change any of the code that uses the API of the class in question).

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-08-05 22:29

It's part of the encapsulation principle. You use setters and getters as an interface to interact with your object so that you can - for example - later add any functionality (like validating input data) without touching the code that uses the class(es).

查看更多
登录 后发表回答