Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the "protected" modifier in Java allow access to other classes in same package?

What is the reason that in Java, a member with a "protected" modifier can not only be accessed by the same class and by subclasses, but also by everyone in the same package?

I am wondering about language design reasons, not actual applications (e.g., testing)

like image 846
Uri Avatar asked May 24 '09 02:05

Uri


2 Answers

This design is based on the idea that the package is the appropriate unit, maintained and released by one internally consistent team; inheritance relationships have much less to do with who's maintaining and releasing what when.

like image 197
Alex Martelli Avatar answered Oct 06 '22 01:10

Alex Martelli


The modifiers are well-described at http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html. From there we see this figure.

Modifier        Class     Package   Subclass  World public          Y         Y         Y         Y protected       Y         Y         Y         N no modifier     Y         Y         N         N private         Y         N         N         N 

From this the reason for the design decision is obvious: it's to have a nice symmetric matrix.

like image 42
Glenn Avatar answered Oct 06 '22 00:10

Glenn