3

I know what the Java protected keyword is, that it is accessible to the class, package, subclass, but not the world.

My question is, when should I use protected?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
MarkusWillson
  • 411
  • 1
  • 3
  • 11
  • 7
    You should do exactly what you said: when you want something that it is accessible to the class, package, subclass, but not the world. Could you please clarify your question to explain what you are asking? – 416E64726577 Nov 30 '14 at 21:19
  • when you need to use it :P – Pravin Nov 30 '14 at 21:22
  • 1
    give it an hour or two before closing. the accepted answer to the first alleged duplicate does not clearly answer "*when* should i use protected". the second alleged duplicate is pretty neglected with just 3 answers and it is also not really focused on the "when protected". DO NOT degrade stackoverflow by preventing good answers from emerging. Or, at least if you close, you should explain why you think a square peg fits a round hole. – necromancer Nov 30 '14 at 21:35
  • 1
    @necromancer I closed this question as a duplicate of the question with three answers, because the second paragraph of [the accepted answer](http://stackoverflow.com/a/8353371/1247781) addresses exactly when to use protected and what to keep in mind when doing so. That question itself asks when to use private and when to use protected, making this one a duplicate. – FThompson Nov 30 '14 at 21:36
  • I closed it because it is too broad. And it is. And it is unclear: the reasons to use it are stated, what's the point of the question? It's a bad question all around. – Jeroen Vannevel Nov 30 '14 at 21:38

2 Answers2

3

You should use protected in that case, when you want the element to be accessible to the class, package, subclass, but not the world. This is very useful, if you make the program whit a large number of other programmers and you don't want them to change your variables but you want to be able to make subclasses which can do that.

szentsas
  • 131
  • 4
2

You use protected in a class that is intented to be used as a base class and you want to access some methods or attributes from the derived classes even if they are not in same package and without making them public.

It is commonly used in frameworks. There is generally an interface that defines the public API, and a base class (often abstract) that is intended to be derived. In the derived class, the overriden methods may make use of some protected methods and or attributes. That way :

  • those methods need not be public
  • the derived class may be in implementor's package not in framework one.
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252