使用公共getter / setter访问同一个类中的私有变量,或直接访问变量 [英] Use public getters/setters to access private variables in the same class, or access the variables directly

查看:154
本文介绍了使用公共getter / setter访问同一个类中的私有变量,或直接访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习编程,虽然我觉得我对编程有很好的了解(多年来一直在编写PHP,Javascript等),但我从未潜入过OOP世界。因此,我要求对我所处的情况作一般性答案。我知道总会有一些例外情况,但在这种情况下我正在寻找最正确的方法。

I am studying programming and although I feel like I have good knowledge in programming (been writing PHP, Javascript etc for years), I've never dived into the world of OOP. Because of this I am asking for a general answer for the situation I am in. I know that there always will be some exceptions, but I am looking for the most correct approach in this case.

好的,所以我有两个班级,游戏 GameGraphics GameGraphics 将创建一个 Game 的对象,并使用它拥有的所有方法。我们最近了解到一个类的所有变量都应该是私有的,所以 Game 中的所有变量都是通过getter访问 GameGraphics 和setter。

Ok, so I have two classes, Game and GameGraphics. GameGraphics will create an object of Game and use all the methods it has. We recently learned that all variables a class should be private, so all the variables in Game are accessed by GameGraphics through getters and setters.

但是,当我想在中访问 Game 的变量时游戏类,我应该使用公共方法,还是直接访问变量?对此最正确的方法是什么?

But, when I want to access the variables of Game inside the Game class, should I use the public methods, or just access the variables directly? What is the most correct approach to this?

我正在用Java开发,如果这很重要的话。请原谅我缺乏OOP经验。

I'm developing in Java, if that matters. And please excuse my lack of OOP-experience.

推荐答案

使用访问器方法(getter和setter)访问的两个主要原因其他类的变量是

The two major reasons behind using accessor methods (getters and setters) to access variables of other classes are


  • 将访问者作为界面成员呈现的能力,

  • 能够覆盖子类中的访问者。

可读性的轻微下降是为这些优势付出的合理代价,因为它们是让你封装你的类的逻辑,从而更严格地控​​制你。

A slight drop in readability is a reasonable price to pay for these advantages, because they let you encapsulate the logic of your class, resulting in tighter control on your part.

这些优点在私有方法中都不适用:它们不能实现接口方法,他们不能被覆盖。实际上,Java编译器通常会完全优化它们,尤其是更简单的。

Neither of these advantages applies when it comes to private methods: they cannot implement interface methods, and they cannot be overridden. In fact, Java compiler would often optimize them out altogether, especially the simpler ones.

这就是为什么我建议直接使用实例变量,而不是添加额外的这个层没有帮助的可读性,但是被编译器优化了。

That is why I would recommend going straight for the instance variables, rather than adding an extra layer that does not help readability, yet gets optimized out by the compiler.

这篇关于使用公共getter / setter访问同一个类中的私有变量,或直接访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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