问题
Are classes private or public by default in Java and C++?
回答1:
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.
回答2:
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. :)
回答3:
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.
来源:https://stackoverflow.com/questions/12336814/is-a-class-private-or-public-by-default-in-java-and-c