Access modifiers in java : public, protected, default, private

In Java, access modifiers are keywords that help setting the accessibility of classes, methods or members. There are four access modifiers in Java language, they are exposed in the following from the least restrictive (public) to the most restrictive (private).

 

Public

Means that the class or the member variable or method can be accessed from anywhere in the code, from the same package or from a different one.

Protected

Can be used with inner variables, methods or inner classes. This access modifier means that the member can be accessed only from the same class or a subclass.

Default (or package private)

This is the default access modifier that will be applied when we don’t specify any. It can be used with a class or member variable or method.
It means that the member can be accessed only from the same package. Please note that a default member cannot be accessed from a subclass in an other package as well.

Private

The private keyword can be used for members (variables, methods or inner classes , when used it limits access to members to only the same class only.

Note

The native keyword in java is not considered as an access modifier.

Summary

class package Sub-class

(same package)

Sub-class

(other package)

World
public  ✔  ✔  ✔  ✔
Protected  ✔  ✔  ✔  ✔  x
default  ✔  ✔  ✔  x  x
private  ✔  x  x  x  x
You like this content ? Share it with you entourage !