Access modifier protected [closed]

1

A common class (which is not subclassed) and has no inheritance, can you use a protected attribute of a superclass that has a subclass? If yes, is this attribute visible (without using the get and set methods of the superclass)?

    
asked by anonymous 13.05.2018 / 02:35

3 answers

1

No. One can not speak of inheritance when the premise is that there will be no inheritance. So the question does not even make sense.

If there was inheritance there the field (I do not consider it correct to call attribute, notice in the question how confusing to have two things using the term attribute) will be visible in this class that inherited another and has a field with attribute protected in your declaration. It will not be visible elsewhere.

    
13.05.2018 / 02:45
0

You can dribble all this, inheritance and access level, with Reflection . Then you access properties and fields private , protected , whatever. It will hardly be the best way to solve your problem, but it works.

If you give more details I can provide an example code.

    
14.05.2018 / 19:49
0

There are two things we can observe in this question:

  • You want to access a protected field of a class. This is a bad smell that you are using this class for a different purpose for which it was created. A class, in the perfect scenario, must have only one purpose and responsibility (the famous Single Responsibility), so your strategy may not be the best.
  • A class with a protected field is not a superclass of any other, it is also a bad smell indicating that this class was poorly planned in its creation. Otherwise, this field would probably be private . Validate the context of this class and its use in the system to know if this is the case. If it is, a refactoring is valid, to use it the way you have in mind.
  • 14.05.2018 / 21:33