Access modifiers in Java are used to define the accessibility and scope of a class or data variable. An access modifier must be specified whenever a variable or method is being defined.
There are 4 access modifiers in Java:
Private
: This access modifier ensures that a member can only be accessed from within the class. Java does not offer the Private
word with a class.
Public
: This access modifier allows the data variable or method to be accessed anywhere. A variable can be accessed within the class or outside the class.
Protected
: In a child class, the protected modified variable can be accessed within the package and outside the package. The access level of a protected modifier is only inside and outside the package through the child class.
Default
: The default access modified variable can only be accessed within the same package. The variable cannot be accessed outside the package. If no access modifier is mentioned, then the Default
modifier is automatically added.
Modifier | Class | Package | Sub-class | Global |
---|---|---|---|---|
Public |
Yes | Yes | Yes | Yes |
Private |
Yes | No | No | No |
Default |
Yes | Yes | No | No |
Protected |
Yes | Yes | Yes | No |
RELATED TAGS
View all Courses