且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么Checkstyle中默认不允许使用受保护的变量?

更新时间:2023-11-14 23:18:16

从理论上讲,受保护的属性(变量)是面向对象语言中的反模式。如果只有子类需要访问其超类的成员属性,则将属性本身定义为private,并创建受保护的访问器方法(getter和setter)。这种方法适用于信息隐藏的概念。还有另一种解决方案:定义受保护的不可变(最终)成员属性。

Theoretically, protected attributes (variables) are an anti-pattern in object-oriented languages. If only subclasses need to access member attributes of its superclass, define the attributes themselves as private and create protected accessor methods (getter and setter). This approach applies the concept of 'information hiding'. There is an alternative solution: define protected immutable (final) member attributes.

进一步的读数:

  • Should you ever use protected member variables?
  • http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html