Search code examples
javainheritancevisibilityprotectedaccess-specifier

Why is a protected variable visible at class level?


A protected variable is access to any class within a package and only to a subclass that extends the base class outside the package.

Why did Java implemented this in this was i.e default within package instead of private within package?
This is defeating the whole purpose of having blocking access to your variables.

The definition of protected access modifier in java is that if you define classA has a protected variable x -- then x is visible to every class in the same package and it is also visible to any class outside the package but extends classA. I feel that within the package level it should be private instead of default access. I am sure Java might have a good reason behind it, and I want to know what this might be.


Solution

  • A Java "package" is a bunch of classes that are (by definition) implemented by the same guy, and (generally) work together. Hiding data from your own package is counterproductive — you're supposed to trust everything in your package, because you wrote it all.

    If you really want to absolutely hide a variable from everybody (even other classes within your package), just make it "private".