Access modifiers


Access modifiers are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.
In C++, there are only three access modifiers. C# extends the number of them to six, while Java has four access modifiers, but three keywords for this purpose. In Java, having no keyword before defaults to the package-private modifier.
When the class is declared as public, it is accessible to other classes defined in the same package as well as those defined in other packages. This is the most commonly used specifier for classes. However, a class itself cannot be declared as private. If no access specifier is stated, the default access restrictions will be applied. The class will be accessible to other classes in the same package but will be inaccessible to classes outside the package. When we say that a class is inaccessible, it simply means that we cannot create an object of that class or declare a variable of that class type. The protected access specifier too cannot be applied to a class.

Names of keywords

C++ uses the three modifiers called public, protected, and private. C# has the modifiers public, protected ,internal, private, protected internal, and private protected. Java has public, package, protected, and private. The access modifier package is the default and used, if any other access modifier keyword is missing. The meaning of these modifiers may differ from one language to another. A comparison of the keywords, ordered from the most restrictive to the most open, and their meaning in these three languages follows. Their visibility ranges from the same class to the package where the class is defined to a general access permission. Below, the maximal access is written into the table.
KeywordC#C++Java
privateclassclass
and/or
friend classes
class
private protectedderived classes in the same assembly--
protected internalsame assembly
and/or
derived classes
--
protectedderived classesderived classes
and/or
friend classes
derived classes
and/or
within same package
package--within its package
internalsame assembly--
publiceverybodyeverybodyeverybody

Example in C++


  1. include
  2. include
using std::cout;
using std::endl;
struct B ;
struct D : B ;
int main