<p>I seldom use inheritance, but when I do, I never use protected attributes because I think it breaks the encapsulation of the inherited classes.</p>

<p>Do you use protected attributes ? what do you use them for ?</p>

[{'answer_id': 76224, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 3, 'selected': False, 'text': "<p>You may need them for static (or 'global') attribute you want your subclasses or classes from same package (if it is about java) to benefit from.</p>\n\n<p>Those static final attributes representing some kind of 'constant value' have seldom a getter function, so a protected static final attribute might make sense in that case.</p>\n"}, {'answer_id': 76225, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 2, 'selected': False, 'text': "<p>I don't use protected attributes in Java because they are only package protected there. But in C++, I'll use them in abstract classes, allowing the inheriting class to inherit them directly.</p>\n"}, {'answer_id': 76228, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 3, 'selected': False, 'text': "<p>C#:</p>\n\n<p>I use protected for abstract or virtual methods that I want base classes to override.  I also make a method protected if it may be called by base classes, but I don't want it called outside the class hierarchy.</p>\n"}, {'answer_id': 76231, 'author': 'cynicalman', 'author_id': 410, 'author_profile': 'https://Stackoverflow.com/users/410', 'pm_score': 2, 'selected': False, 'text': "<p>There are never any good reasons to have protected attributes.  A base class must be able to depend on state, which means restricting access to data through accessor methods.  You can't give anyone access to your private data, even children.</p>\n"}, {'answer_id': 76238, 'author': 'Dan Blair', 'author_id': 1327, 'author_profile': 'https://Stackoverflow.com/users/1327', 'pm_score': 1, 'selected': False, 'text': "<p>In general, no you really don't want to use protected data members.  This is doubly true if your writing an API.  Once someone inherits from your class you can never really do maintenance and not somehow break them in a weird and sometimes wild way.  </p>\n"}, {'answer_id': 76243, 'author': 'terminus', 'author_id': 9232, 'author_profile': 'https://Stackoverflow.com/users/9232', 'pm_score': 1, 'selected': False, 'text': "<p>I use them. In short, it's a good way, if you want to have some attributes shared. Granted, you could write set/get functions for them, but if there is no validation, then what's the point? It's also faster.</p>\n\n<p>Consider this: you have a class which is your base class. It has quite a few attributes you wan't to use in the child objects. You could write a get/set function for each, or you can just set them.</p>\n\n<p>My typical example is a file/stream handler. You want to access the handler (i.e. file descriptor), but you want to hide it from other classes. It's way easier than writing a set/get function for it.</p>\n"}, {'answer_id': 76248, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 1, 'selected': False, 'text': '<p>I think protected attributes are a bad idea. I use <a href="http://checkstyle.sourceforge.net/" rel="nofollow noreferrer">CheckStyle</a> to enforce that rule with my Java development teams.</p>\n'}, {'answer_id': 76277, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 1, 'selected': False, 'text': "<p>In general, yes.  A protected method is usually better.</p>\n\n<p>In use, there is a level of simplicity given by using a protected <strong>final</strong> variable for an object that is shared by all the children of a class.  I'd always advise against using it with primitives or collections since the contracts are impossible to define for those types.</p>\n\n<p>Lately I've come to separate stuff you do with primitives and raw collections from stuff you do with well-formed classes.  Primitives and collections should ALWAYS be private.</p>\n\n<p>Also, I've started occasionally exposing public member variables when they are declaired final and are well-formed classes that are not too flexible (again, not primitives or collections). </p>\n\n<p>This isn't some stupid shortcut, I thought it out pretty seriously and decided there is absolutely no difference between a public <strong>final</strong> variable exposing an object and a getter.</p>\n"}, {'answer_id': 76286, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': "<p>Scott Meyers says <em>don't</em> use protected attributes in Effective C++ (3rd ed.):</p>\n\n<blockquote>\n  <p>Item 22: Declare data members private.</p>\n</blockquote>\n\n<p>The reason is the same you give: it breaks encapsulations. The consequence is that otherwise local changes to the layout of the class might break dependent types and result in changes in many other places.</p>\n"}, {'answer_id': 87360, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 2, 'selected': False, 'text': '<p>I recently worked on a project were the "protected" member was a very good idea. The class hiearchy was something like:</p>\n\n<pre><code>[+] Base\n |\n +--[+] BaseMap\n |   |\n |   +--[+] Map\n |   |\n |   +--[+] HashMap\n |\n +--[+] // something else ?\n</code></pre>\n\n<p>The Base implemented a std::list but nothing else. The direct access to the list was forbidden to the user, but as the Base class was incomplete, it relied anyway on derived classes to implement the indirection to the list.</p>\n\n<p>The indirection could come from at least two flavors: std::map and stdext::hash_map. Both maps will behave the same way but for the fact the hash_map needs the Key to be hashable (in VC2003, castable to size_t).</p>\n\n<p>So BaseMap implemented a TMap as a templated type that was a map-like container.</p>\n\n<p>Map and HashMap were two derived classes of BaseMap, one specializing BaseMap on std::map, and the other on stdext::hash_map.</p>\n\n<p>So:</p>\n\n<ul>\n<li><p>Base was not usable as such (no public accessors !) and only provided common features and code</p></li>\n<li><p>BaseMap needed easy read/write to a std::list</p></li>\n<li><p>Map and HashMap needed easy read/write access to the TMap defined in BaseMap.</p></li>\n</ul>\n\n<p>For me, the only solution was to use protected for the std::list and the TMap member variables. There was no way I would put those "private" because I would anyway expose all or almost all of their features through read/write accessors anyway.</p>\n\n<p>In the end, I guess that if you en up dividing your class into multiple objects, each derivation adding needed features to its mother class, and only the most derived class being really usable, then protected is the way to go. The fact the "protected member" was a class, and so, was almost impossible to "break", helped.</p>\n\n<p>But otherwise, protected should be avoided as much as possible (i.e.: Use private by default, and public when you must expose the method).</p>\n'}, {'answer_id': 1546563, 'author': 'Pascal Thivent', 'author_id': 70604, 'author_profile': 'https://Stackoverflow.com/users/70604', 'pm_score': 5, 'selected': True, 'text': '<p>In this <a href="http://www.artima.com/intv/blochP.html" rel="noreferrer">interview</a> on Design by Bill Venners, Joshua Bloch, the author of <em>Effective Java</em> says:</p>\n\n<blockquote>\n  <h2>Trusting Subclasses</h2>\n  \n  <p><strong>Bill Venners:</strong> <em>Should I trust subclasses more intimately than\n  non-subclasses? For example, do I make\n  it easier for a subclass\n  implementation to break me than I\n  would for a non-subclass? In\n  particular, how do you feel about\n  protected data?</em></p>\n  \n  <p><strong>Josh Bloch:</strong> To write something that is both subclassable and robust\n  against a malicious subclass is\n  actually a pretty tough thing to do,\n  assuming you give the subclass access\n  to your internal data structures. If\n  the subclass does not have access to\n  anything that an ordinary user\n  doesn\'t, then it\'s harder for the\n  subclass to do damage. But unless you\n  make all your methods final, the\n  subclass can still break your\n  contracts by just doing the wrong\n  things in response to method\n  invocation. That\'s precisely why the\n  security critical classes like String\n  are final. Otherwise someone could\n  write a subclass that makes Strings\n  appear mutable, which would be\n  sufficient to break security. So you\n  must trust your subclasses. If you\n  don\'t trust them, then you can\'t allow\n  them, because subclasses can so easily\n  cause a class to violate its\n  contracts.</p>\n  \n  <p>As far as protected data in general,\n  it\'s a necessary evil. It should be\n  kept to a minimum. Most protected data\n  and protected methods amount to\n  committing to an implementation\n  detail. A protected field is an\n  implementation detail that you are\n  making visible to subclasses. Even a\n  protected method is a piece of\n  internal structure that you are making\n  visible to subclasses.</p>\n  \n  <p>The reason you make it visible is that\n  it\'s often necessary in order to allow\n  subclasses to do their job, or to do\n  it efficiently. But once you\'ve done\n  it, you\'re committed to it. It is now\n  something that you are not allowed to\n  change, even if you later find a more\n  efficient implementation that no\n  longer involves the use of a\n  particular field or method.</p>\n  \n  <p>So all other things being equal, you\n  shouldn\'t have any protected members\n  at all. But that said, if you have too\n  few, then your class may not be usable\n  as a super class, or at least not as\n  an efficient super class. Often you\n  find out after the fact. My philosophy\n  is to have as few protected members as\n  possible when you first write the\n  class. Then try to subclass it. You\n  may find out that without a particular\n  protected method, all subclasses will\n  have to do some bad thing.</p>\n  \n  <p>As an example, if you look at\n  <code>AbstractList</code>, you\'ll find that there\n  is a protected method to delete a\n  range of the list in one shot\n  (<code>removeRange</code>). Why is that in there?\n  Because the normal idiom to remove a\n  range, based on the public API, is to\n  call <code>subList</code> to get a sub-<code>List</code>,\n  and then call <code>clear</code> on that\n  sub-<code>List</code>. Without this particular\n  protected method, however, the only\n  thing that <code>clear</code> could do is\n  repeatedly remove individual elements.</p>\n  \n  <p>Think about it. If you have an array\n  representation, what will it do? It\n  will repeatedly collapse the array,\n  doing order N work N times. So it will\n  take a quadratic amount of work,\n  instead of the linear amount of work\n  that it should. By providing this\n  protected method, we allow any\n  implementation that can efficiently\n  delete an entire range to do so. And\n  any reasonable <code>List</code> implementation\n  can delete a range more efficiently\n  all at once.</p>\n  \n  <p>That we would need this protected\n  method is something you would have to\n  be way smarter than me to know up\n  front. Basically, I implemented the\n  thing. Then, as we started to subclass\n  it, we realized that range delete was\n  quadratic. We couldn\'t afford that, so\n  I put in the protected method. I think\n  that\'s the best approach with\n  protected methods. Put in as few as\n  possible, and then add more as needed.\n  Protected methods represent\n  commitments to designs that you may\n  want to change. You can always add\n  protected methods, but you can\'t take\n  them out.</p>\n  \n  <p><strong>Bill Venners:</strong> <em>And protected data?</em></p>\n  \n  <p><strong>Josh Bloch:</strong> The same thing, but even more. Protected data is even more\n  dangerous in terms of messing up your\n  data invariants. If you give someone\n  else access to some internal data,\n  they have free reign over it.</p>\n</blockquote>\n\n<p>Short version: it breaks encapsulation but it\'s a necessary evil that should be kept to a minimum.</p>\n'}, {'answer_id': 2034079, 'author': 'Calmarius', 'author_id': 58805, 'author_profile': 'https://Stackoverflow.com/users/58805', 'pm_score': 1, 'selected': False, 'text': '<p>It depends on what you want. If you want a fast class then data should be protected and use protected and public methods.\nBecause I think you should assume that your users who derive from your class know your class quite well or at least they have read your manual at the function they going to override.</p>\n\n<p>If your users mess with your class it is not your problem. Every malicious user can add the following lines when overriding one of your virtuals:</p>\n\n<p>(C#)</p>\n\n<pre><code>static Random rnd=new Random();\n//...\nif (rnd.Next()%1000==0) throw new Exception("My base class sucks! HAHAHAHA! xD");\n//...\n</code></pre>\n\n<p>You can\'t seal every class to prevent this.</p>\n\n<p>Of course if you want a constraint on some of your fields then use accessor functions or properties or something you want and make that field private because there is no other solution...</p>\n\n<p>But I personally don\'t like to stick to the oop principles at all costs. Especially making properties with the only purpose to make data members private.</p>\n\n<p>(C#):</p>\n\n<pre><code>private _foo;\npublic foo\n{\n   get {return _foo;}\n   set {_foo=value;}\n}\n</code></pre>\n\n<p>This was my personal opinion.</p>\n\n<p>But do what your boss require (if he wants private fields than do that.)</p>\n'}, {'answer_id': 2034129, 'author': 'David R Tribble', 'author_id': 170383, 'author_profile': 'https://Stackoverflow.com/users/170383', 'pm_score': 1, 'selected': False, 'text': "<p>I use protected variables/attributes within base classes that I know I don't plan on changing into methods. That way, subclasses have full access to their inherited variables, and don't have the (artificially created) overhead of going through getters/setters to access them. An example is a class using an underlying I/O stream; there is little reason not to allow subclasses direct access to the underlying stream.</p>\n\n<p>This is fine for member variables that are used in direct simple ways within the base class and all subclasses. But for a variable that has a more complicated use (e.g., accessing it causes side effects in other members within the class), a directly accessible variable is not appropriate. In this case, it can be made private and public/protected getters/setters can be provided instead. An example is an internal buffering mechanism provided by the base class, where accessing the buffers directly from a subclass would compromise the integrity of the algorithms used by the base class to manage them.</p>\n\n<p>It's a design judgment decision, based on how simple the member variable is, and how it is expected to be so in future versions.</p>\n\n<p>Encapsulation is great, but it can be taken too far. I've seen classes whose own private methods accessed its member variables using only getter/setter methods. This is overkill, since if a class can't trust its own private methods with its own private data, who can it trust?</p>\n"}, {'answer_id': 36660453, 'author': 'Jim Balter', 'author_id': 544557, 'author_profile': 'https://Stackoverflow.com/users/544557', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>protected</code> keyword is a conceptual error and language design botch, and several modern languages, such as Nim and Ceylon (see <a href="http://ceylon-lang.org/documentation/faq/language-design/#no_protected_modifier" rel="nofollow noreferrer">http://ceylon-lang.org/documentation/faq/language-design/#no_protected_modifier</a>), that have been carefully designed rather than just copying common mistakes, don\'t have such a keyword.</p>\n\n<p>It\'s not protected members that breaks encapsulation, it\'s exposing members that shouldn\'t be exposed that breaks encapsulation ... it doesn\'t matter whether they are protected or public. The problem with <code>protected</code> is that it is wrongheaded and misleading ... declaring members <code>protected</code> (rather than <code>private</code>) doesn\'t protect them, it does the opposite, exactly as <code>public</code> does. A protected member, being accessible outside the class, is exposed to the world and so its semantics must be maintained forever, just as is the case for <code>public</code>. The whole idea of "protected" is nonsense ... encapsulation is not security, and the keyword just furthers the confusion between the two. You can help a little by avoiding all uses of <code>protected</code> in your own classes -- if something is an internal part of the implementation, isn\'t part of the class\'s semantics, and may change in the future, then make it private or internal to your package, module, assembly, etc. If it is an unchangeable part of the class semantics, then make it public, and then you won\'t annoy users of your class who can see that there\'s a useful member in the documentation but can\'t use it, unless they are creating their own instances and can get at it by subclassing.</p>\n'}]
['https://Stackoverflow.com/questions/76194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13501/']