为什么要声明getter和setter方法是私有的? [英] Why would you declare getters and setters method private?

查看:101
本文介绍了为什么要声明getter和setter方法是私有的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一个代码,其中getter和setter方法被声明为private。我试图找出它背后的逻辑,我真的很难理解为什么你会将它们声明为私有?这与我们试图通过getter和setter实现的完全相反。

I saw a code where getters and setters methods are declared private. I am trying to figure out the logic behind it, and I am really having hard time to understand why would you declare them as private? That's exactly opposite of what we are trying to achieve through getters and setters.

推荐答案

我可以想到几个原因:


  • 您希望阻止将来公开访问。

如果一个不同的程序员看到你的代码并希望访问一个变量,但是没有setter和getter,他可能会认为你只是忘记了它们,并自己添加它们。但是,如果您将它们声明为 private ,那么它是一个意图声明,说我不希望从外部更改或访问这些变量

If a different programmer sees your code and wants access to a variable, but there are no setters and getters, he might think you just forgot about them, and add them themselves. However, if you declare them as private, it's a statement of intent, saying I don't want these variables to be changed or accessed from the outside.


  • 您想要设置和获取其他操作

假设你不想要 public 访问者。但也许你想要计算私有变量被改变的次数。每次访问该变量时,使用setter更容易,而不是递增计数。

Say you don't want public accessors. But maybe you want a count of how many times a private variable is changed. It's easier to use a setter rather than incrementing the count every time you access that variable.


  • 你想要一个中央访问点

同样,您不希望 public 访问,但在调试期间,您可能希望在每个地方放置一个断点, private 成员被更改。因此,不要在类中的任何地方设置断点,而只需在访问器中设置一个断点。

Again, you don't want public access, but during debugging, you might want to put a breakpoint in every place a private member is changed. So instead of setting breakpoints everywhere in the class, you just set one in the accessor.

这篇关于为什么要声明getter和setter方法是私有的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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