Which class members were the modifier supposed to protect?

I know what the Java keyword is protected

, that it is available to a class, package, subclass, but not the world.

My question is when should I use protected

?

+3


source to share


2 answers


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



+3


source


You are using protected in a class that is intended to be used as a base class, and you want to access some methods or attributes from derived classes, even if they are not in the same package and do not publish them.

It is usually used in frames. Usually there is an interface that defines a public API and a base class (often abstract) that should be obtained. In a derived class, overridden methods can use some protected methods and / or attributes. Thus:



  • These methods should not be publicly available.
  • the derived class may not be in the same implementation package.
+2


source







All Articles