Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 714
M.J. Avatar asked Oct 06 '10 04:10

M.J.


People also ask

Can a class be declared as protected?

No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier).

How do you define a protected class in Java?

Protected Access Modifier - Protected Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces.

Why protected modifier is not allowed in Java?

what is the reason? You cannot use the protected access modifier for top level classes. The protected modifier means that the member can only be accessed within its own package or by a subclass of its class in another package. At top level you can only use the public modifier or no modifier (package-private).

Why can't we declare a class as private in Java?

If you have a private inner or nested class, then access is restricted to the scope of that outer class. If you have a private class on its own as a top-level class, then you can't get access to it from anywhere. So it does not make sense to have a top level private class.


2 Answers

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.

like image 133
Nikita Rybak Avatar answered Oct 18 '22 15:10

Nikita Rybak


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.

like image 30
Akash5288 Avatar answered Oct 18 '22 13:10

Akash5288