Are classes private or public by default in Java and C++?
4 Answers
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.
-
See also answer here: https://stackoverflow.com/a/4855490/2336934 – dan Aug 24 '21 at 20:39
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. :)

- 86,166
- 18
- 182
- 232
-
Thanks for the comment but the link you sent speaks of access modifiers for class members, not the classes themselves. Top level classes cannot be marked private. – Ray Toal Oct 12 '21 at 04:34
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.

- 29,212
- 3
- 44
- 57
-
3+1. Also, in C++ class default member access is `private`, whereas for `struct` it is public. – juanchopanza Sep 09 '12 at 08:17
Java
By default Java class is package-private.
C++
In C++ there is no visibility defined like Java.

- 1
- 1
-
Welcome to Stack Overflow. You could improve your answer by explaining what "default" is for Java. I.e., `class Foo` w/o a visibility modifier is package-private. You could also quote https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html or at least link to it. For C++, you could explain on your answer with an example and explanation. – Oliver Dec 28 '22 at 03:34