Is a class private or public by default in Java and C++?

和自甴很熟 提交于 2019-11-29 01:05:56
zeller
  • 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.

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. :)

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!