Access modifier protected

Asked

Viewed 450 times

1

A common class (which is not subclass) and has no inheritance, can use an attribute protected of a superclass that has a subclass? If so, this attribute will be visible (no need to use the superclass’s get and set methods)?

  • If you are not subclass and have no inheritance, which is the superclass ?

  • Every class, after all, is a subclass of Object, so - being pretty boring - technically there’s always some heritage involved. Anyway, see if the link above (the possible duplicate) already has the information you need. If not, please feel free to [Dit] your question, explaining why the other question did not resolve your question.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

1

No. One cannot speak of inheritance when the premise is that there will be no inheritance. So the question even makes sense.

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

0

There are two things we can observe in your doubt:

  1. You want to access a field protected of a class. That’s a bad Smell that you’re using this class for a different purpose for which it was created. A class, in the perfect setting, must have only one purpose and responsibility (the famous Single Responsibility), so your strategy may not be the best.
  2. A class with a field protected not being 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 see if this is the case. If it is, a refactoring is valid, to use it the way you have in mind.

0

You can circumvent all this, heritage and access level, with Reflection. Then you access properties and fields private, protected, whatever it is. It’s hardly the best way to solve your problem, but it works.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.