Why can't we define a top level class as private?

前端 未结 10 2118
情书的邮戳
情书的邮戳 2020-12-07 12:38

Why does Java not allow a top level class to be declared as private? Is there any other reason other than \"We can\'t access a private class\"?

10条回答
  •  借酒劲吻你
    2020-12-07 13:05

    In theory, you could instantiate and call methods on a private top-level class (if such a thing were allowed by the language ... which it isn't!), but you would have to use reflection to do this. Sensibly (IMO) Sun decided that private top-level classes were not a good thing to support at the language level.

    Actually, it is possible that the JVM might support top-level private "classes" created by bytecode magic. But it is not a useful thing to do.


    UPDATE - In fact, the current JVM spec makes it clear that the ACC_PRIVATE bit of the access flags word for a class is "reserved for future use", and that Java implementations should treat it as unset. Thus, the above speculation is moot for any JVM that strictly implements the current specification.

提交回复
热议问题