Why can a class not be defined as protected?

后端 未结 12 2111
长发绾君心
长发绾君心 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:45

    What makes sense to this question is that, JVM is written in C (Sun JVM) and C++(oracle JVM) so during compilation, we are going to create .class files out of our java file and if we declare a class with Protected keyword then it will not be accessed by JVM.

    The answer why protected class will not be accessed by JVM is that, since protected fields are accessible within same package or to diffrent package through inheritance only and JVM is not written in a way so that it will inherit will class. Hope this satisfies this question :)

    Similarly, A top level class can't be private. Explanation as below:

    So what will happen if we will define a class private, that class will only be accessible within the entity in which it is defined which in our case is its package?

    So defining private access to the class will make it accessible inside the same package which default keyword already do for us, Therefore there is no benefit of defining a class private it will only make things ambiguous.

提交回复
热议问题