Why can a class not be defined as protected?

后端 未结 12 2123
长发绾君心
长发绾君心 2020-12-04 08:03

Why can we not define a class as protected?

I know that we can\'t, but why? There should be some specific reason.

12条回答
  •  Happy的楠姐
    2020-12-04 08:56

    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.

提交回复
热议问题