Why are protected variables not allowed by default in Checkstyle?

前端 未结 3 1321
旧时难觅i
旧时难觅i 2021-01-03 18:07

I get a lot of warnings in eclipse like these:

Variable \'myVariable\' must be private and have accessor methods.

I think I get

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 18:27

    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.

    Further readings:

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

提交回复
热议问题