The process of hiding information is implemented using Access Specifiers known as visibility modifiers. They regulate access to classes, fields, and methods. Access Specifiers specify if fields or methods in a class can be invoked from another class or sub-class. In simple words, they are used to restrict access.
There are four types of Access Specifiers in Java.
- Public
- Private
- Protected
- Default (no specifier)
Public: Classes, methods, and fields declared as public can be accessed from any class in an application.
Default: If Classes, variables, and methods have a default specifier we can access them only within the same package but not from outside this package.
When no access specifiers are specified for an element, its accessibility level is the default. There is no keyword default. (alert-passed)
Private: Private methods and fields can only be accessed within the same class to which the methods and field belong.
Protected: Protected methods and fields are accessible within the package and outside the package but with the help of inheritance. It cannot be applied to a class and it provides more accessibility than the default access specifier.
Access Modifiers | default | private | protected | public |
---|---|---|---|---|
Accessible inside the class | Yes | Yes | Yes | Yes |
Accessible within the subclass inside the same package | Yes | No | Yes | Yes |
Accessible outside the package | No | No | No | Yes |
Accessible within the subclass outside the package | No | No | Yes | Yes |
No comments:
Post a Comment