116. 'Package' and Access Protection

Now we know how to organize our class files by categorizing the class files into several packages in a project. But there is one more thing you have to know about packages i.e. package provide protection to the code of class files under it from being modified by the code outside the package based on the specified access specifier 'public', 'private' and 'protected'.

So to rewind the access specifiers of Java:
  • Anything declared public can be accessed from anywhere
  • Anything declared private cannot be accessed outside the class
  • Anything declared protected can be accessed by the sub classes or other classes inside the same package but not accessed outside the package. protected members can be accessed outside the package, if and only if there is a subclass of protected members class outside the package.
So if you want your elements to be seen outside the package, but only to classes that subclass your class directly, then declare that element as protected.

Finally use the below table to find out the accessibility of your class members when specified as private, public, protected and also when not specified with anything:

Please comment below to feedback or ask questions.

'Importing Packages' topic will be explained in the next post.

1 comment:

Lalitha Jyothi said...

Can you please give me an example using protected access modifier