Why can a class not be defined as protected?

后端 未结 12 2104
长发绾君心
长发绾君心 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条回答
  •  离开以前
    2020-12-04 08:53

    The answer from @Akash5288 made no sense to me:

    If all the classes are allowed to subclass then it will be similar to public access specifier.

    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.

    You can then apply the same logic to protected methods and variables, they are also then "similar to public". All classes outside of a package can extend our public class and use its protected methods. Why is restricting methods and variables to extended classes ok, but restricting the whole class not ok? "Similar to public" is not "same as public". My interpretation is that it is perfectly fine to allow a protected class, as it is fine to allow protected methods.

    The answer "you can not extend a class you can not access/see" is more logical.

提交回复
热议问题