Is a class private or public by default in Java an

2019-01-23 12:04发布

Are classes private or public by default in Java and C++?

3条回答
叼着烟拽天下
2楼-- · 2019-01-23 12:21

According to §6.6.1 of the JLS,

If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.

So, a Java class is by default package-private.

This doesn't apply to C++, however. A class lacks visibility -- only its members can have access control. See §11 of the C++11 standard for information on member access control. Here's an excerpt from ¶1...

A member of a class can be

  • private; that is, its name can be used only by members and friends of the class in which it is declared.
  • protected; that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see 11.4).
  • public; that is, its name can be used anywhere without access restriction.
查看更多
SAY GOODBYE
3楼-- · 2019-01-23 12:23

In Java, a top-level class is either public or non-public. There is no "private". You can only use the public keyword or leave it off. If you leave it off it is non-public, i.e., visible only to other classes in the same package.

A nested class, that is, a class inside of another class, can be made public, package-private, protected, or private, just like any other class member. The default (i.e., the one with no modifier) is package-private, visible only to classes in the same package.

EDIT: Forgot the C++ answer, so see (and upvote) @zeller's answer. :)

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-23 12:29
  • Java:

    By default, the classes visibility is package private, i.e. only visible for classes in the same package.

  • C++:

    The class has no visibility defined like in Java. They are visible if you included them to the compilation unit.

查看更多
登录 后发表回答