Java: Protection Type of Variables, Methods or Classes
There are four levels of protection for variables, methods and Classes in
Java and are listed and described below:
Package Protection (DEFAULT) |
- Default, not an explicit form of protection.
- Variables,Methods or Classes of this type are accessibley only
to all other classes in the same package.
- Even if another package is imported, its package protected
variables, methods and classes are not accessible, they stay hidden.
|
Private |
|
Public |
- Such methods, variables and classes are accessible to other
methods inside or outside the current class or package.
- Declare by preceeding declaration with the word public.
|
Protected |
- Such methods and variables are accessible to all classes inside
the same package but only to subclasses outside the package.
- NOT used for classes.
- Declare by preceeding declaration with the word protected.
- Support ability of subclasses to modify the data in a parent
class even when this parent class is in a different package. Yet,
do not have to declare public and let any class touch the data.
|
Handy-Dandy Cross-Reference Table
|
Same Class |
Sub Class |
Same Package |
Class outside package |
public |
X |
X |
X |
X |
protected |
X |
X |
X |
(only subclasses) |
private |
X |
|
|
|
package protected (default) |
X |
X |
X |
|
|