Skip to content

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 public before 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 public or default visibility. This would not compile:

protected class ProtectedClass {

}
This would compile:
class DefaultClass {

}


Drill

Encapsulation/com.example.encapsulation.drills.BankApp

Encapsulation/com.example.encapsulation.drills.Account * Run the BankApp program. Notice that the class accesses the Account fields directly. * Change the fields in Account to have private visibility. What happens to BankApp? Leave it and we will fix it soon.

(Solution: Account1.java, BankApp1.java)


Prev -- Up -- Next