Tuesday, 22 July 2014

Access Modifers in Java vs C++

Access modifiers enables or disables access to a particular component in a programming language. It could be a variable, method or a class.

in Java the access modifiers behave as follows.

Modifier    | Class | Package | Subclass | World
————————————+———————+—————————+——————————+———————
public      |  y    |    y    |    y     |   y
————————————+———————+—————————+——————————+———————
protected   |  y    |    y    |    y     |   n
————————————+———————+—————————+——————————+———————
no modifier |  y    |    y    |    n     |   n
————————————+———————+—————————+——————————+———————
private     |  y    |    n    |    n     |   n

y: accessible
n: not accessible
 
 
The above figure is copied from stackoverflow, and it illustrates how Java access modifiers behave. In addition to the above explanation it should be noted that in case if there is no access modifier, whether the subclass can access the component depends on where the subclass is. If it is in the same package it can access, and if it is not in the same package it cannot access.


in C++ there is no notion of a package.

A public member is accessible from anywhere outside the class but within a program.
A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.
A protected member variable or function is very similar to a private member but it provides one additional benefit that they can be accessed in child classes which are called derived classes.