|
|
| Access level modifiers |
|
Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:
|
- At the top level - public, or package-private (no explicit modifier).
- At the member level - public, private, protected, or package-private (no explicit modifier).
|
|
The following table shows the access to members permitted by each modifier:
|
| Access Levels |
| Modifier | Class | Package | Subclass | World |
| public | Y | Y | Y | Y |
| protected | Y | Y | Y | N |
| no modifier | Y | Y | N | N |
| private | Y | N | N | N |
|
- The first data column indicates whether the class itself has access to the member defined by the access level. As it is clear from table, a class always has access to its own members.
- The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member.
- The third column indicates whether subclasses of the class - declared outside this package - have access to the member.
- The fourth column indicates whether all classes have access to the member.
|
|
In above table Subclass is in different package. But if Subclass is in same package then the third column values will be:
|
| Access Levels |
| Modifier | Subclass |
| public | Y |
| protected | Y |
| no modifier | Y |
| private | N |
|
It is same as the second column. To understand more see this Application which implements protected, no-modifier and private modifiers.
- Access Level Modifiers Main Class
- Access Level Modifiers SubClass Different Package
- Access Level Modifiers SubClass Same Package
- Main Class (Main Method)
|
|
Let's look at a collection of classes and see how access levels affect visibility. The following figure shows the four classes in this example and how they are related.
|
TClasses and Packages of the Example Used to Illustrate Access Levels.
|
|
The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.
|
| Access Levels |
| Modifier | Alpha | Beta | Alphasub | Gamma |
| public | Y | Y | Y | Y |
| protected | Y | Y | Y | N |
| no modifier | Y | Y | N | N |
| private | Y | N | N | N |
|
| Here, Beta can be a SubClass of Alpha. |
|
|
Comments/Feedback:
Please login to participate |
OneInfoPlace server is currently busy. Please try later. Sorry for the inconvenience |