Visibility
visibility¶
Which classes can access a class, or the fields and methods of a class.
We can change our field and method (and even class) definitions to only allow certain classes to use them.
We do so with access modifiers.
- So far we have placed the access modifier
publicbefore our methods and fields.
Access Modifiers¶
| Modifier | Access |
|---|---|
| public | Methods of any class anywhere have access. |
| protected | Methods of subclasses$ and of any class in the same package have access. |
| (default) | Methods of classes in the same package (directory) have access |
| private | Only methods defined in the same class have access. |
$ - we will explain subclasses in a later chapter
If a class tries to use something it can't access, the result is a compiler error.
(default) Access¶
We write or say "default" because this is the access a field or method has when you do not add an access modifier: it is Java's "default" access.
The method below has no access modifier, so it is only available to classes in the same package.
static void defaultAccessMethod() {
}
Practice Exercise¶
Classes can have only
publicor default visibility. This would not compile:This would compile:protected class ProtectedClass { }class DefaultClass { }
Drill¶
Encapsulation/com.example.encapsulation.drills.BankApp
Encapsulation/com.example.encapsulation.drills.Account* Run theBankAppprogram. Notice that the class accesses theAccountfields directly. * Change the fields inAccountto haveprivatevisibility. What happens toBankApp? Leave it and we will fix it soon.(Solution: Account1.java, BankApp1.java)