Access modifiers

In the real world, there will be plenty of objects interacting with one another, and sometimes an object would need to retrieve data stored in other objects or execute operations on them.

The role of access modifiers is to control the level of this access. Access modifiers can be put in front of many java elements like Classes, Variables, Methods, and so on.


Package private

A package private Class method implies that all the Classes that exist in the same package as the Method Class can call it directly with no restriction whereas the classes that live outside cannot. The same level of accessibility applies to variables and classes. There is no key word for package private. To declare a package private java element, you have to remove the access modifier key word.

In the example above, we've three classes. Classes A and B are in the same package access.modifiers.a; whereas Class C is in a different package access.modifiers.b;

The ClassC can call the method MethodA because ClassC and ClassA are in the same Package While ClassB cannot because MethodA is package private and ClassB isn't in access.modifiers.a;

Note that Classes cannot be private or protected because their access level is more restrictive than public and protected, imagine a public method inside a protected class, it doesn't make sense.

Private

When a Class Method or variable is private, it isn't reachable from outside. To declare a private java element, you have to put the private key word in front of it.

the example below doesn't compile because we try to call the private methodA from Class B.

Protected

Protected access modifier is a special one, it is mainly related to the OOP inheritance concept which we didn't explain it so far, but just remember that protected access modifier behaves like package private in addition to the fact that some special classes called children or implementers living outside the main package can access the protected elements of the parent class.

Public

,A Public java element like the Classes defined in the examples above are reachable from everywhere.