Previous | Home | Next |
The visibility modifiers are applicable only on members of a class not on local variables.
- Default / no Modifier
- Public
- Protected
- Private
If no visibility modifier is specified before a member declaration then that member can be accessed from all the classes in the same package. That member can not be accessed outside the package.
If we specify the modifier public with a member variable or method then that member will be visible to all classes. This memberr can be accessed even outside the package. main() method is always defined as public because the main() method is accessed by the jvm which is outside the class in which main() method is defined.
A member declared as protected can be accessed from all the classes belonging to the same package. Protected members can also be accessed from any sub class of other packages.
If we specify the modifier private with a member variable then that member will not be visible outside the class in which it is declared. This will hide the member of a class from other classes.
- Public
- Default / no Modifier
If a class is to be visible to all the classes irrespective of their package, then it must be declared as public by specifying the modifier public, which should appear before the keyword class.
In the absence of any access/visibility modifier before the class, it visibility is only within the package (group of classes) it is defined.
Access Modifier | within class | within package | outside package by subclass only | outside package |
Private | Y | N | N | N |
Default | Y | Y | N | N |
Protected | Y | Y | Y | N |
Public | Y | Y | Y | Y |
Previous | Home | Next |