|
The access modifiers change the accessibility of a class or its member. You can use them to specify who may access the class and its internal constructs. There are four accessibility levels: public, private, protected and default. However, there are only three access modifiers: public, private and protected. If no access modifier is specified, the default access is assumed. The default access is also known as package access. You can use access modifiers in various declarations such as variables, methods and class declarations. For example, if you use a private modifier in the declaration of a member variable, it suggests that the variable is private and accessible only within the class. We will discuss all these four accessibility levels in section 3.2. For now, see following Table 3.1 that shows all the combinations of access modifiers and the declarations in which they can be used.
Table 3.1 Applying access modifiers to classes, member methods and variables.
|
Modifiers |
Top-level Class[††††] |
Inner/nested* Class |
Member Variable |
Member Method |
Constructor |
|
public |
ü |
ü |
ü |
ü |
ü |
|
protected |
- |
ü |
ü |
ü |
ü |
|
(default)[‡‡‡‡] |
ü |
ü |
ü |
ü |
ü |
|
private |
- |
ü |
ü |
ü |
ü |
When you are allowed to use a particular access modifier in the declaration, it is denoted by ü in the table. You can see that the access modifier public can be used in the declarations of top-level class, inner class, member variables, methods and constructors. When access modifier is not applicable, it is denoted with - in the table. For example, you cannot use the private modifier while declaring a top-level class.