Why can a class not be defined as protected?
Why can we not define a class as protected
?
I know that we can't, but why? There should be some specific reason.
Because it makes no sense.
Protected class member (method or variable) is just like package-private (default visibility), except that it also can be accessed from subclasses.
Since there's no such concept as 'subpackage' or 'package-inheritance' in Java, declaring class protected or package-private would be the same thing.
You can declare nested and inner classes as protected or private, though.
As you know default is for package level access and protected is for package level plus non-package classes but which extends this class (Point to be noted here is you can extend the class only if it is visible!). Let's put it in this way:
- protected top-level class would be visible to classes in its package.
- now making it visible outside the package (subclasses) is bit confusing and tricky. Which classes should be allowed to inherit our protected class?
- If all the classes are allowed to subclass then it will be similar to public access specifier.
- If none then it is similar to default.
Since there is no way to restrict this class being subclassed by only few classes (we cannot restrict class being inherited by only few classes out of all the available classes in a package/outside of a package), there is no use of protected access specifiers for top level classes. Hence it is not allowed.
public class A
{
protected class B
{
}
}
Defining a field protected makes that field accessible inside the package as well as outside the package through inheritance only (Only inside the child class).
So If we are allowed to make a class protected then we can access it inside the package very easily but for accessing that class outside of the package we first need to extend that entity in which this class is defined which is its package.
And since a package can not be extended (can be imported), defining a class protected will again make it package-private which is similar to defining it as default which we can already do. Therefore there is no benefit of defining a class private it will only make things ambiguous.
For more information read Why an outer Java class can’t be private or protected