Lesson: 6 Week FIRST Tech Challenge Workshop Controlling access to members of a class

Explore class access control modifier keywords.

Understand access control modifiers for classes.


You have seen the access control modifier public used extensively in our Java examples. The access control modifier is applied to classes and class members (variables and methods) and determines what access code in other classes have to the class members.

Classes can have no access modifier before the class name and will default to package-private. This means the class is only visible to top level classes in the same package. You can also use public, which means the class is visible inside and outside of its package.

At the member level, things get a bit more complicated. You can use access modifiers of public, private, protected or the default, package-private (when no modifier is specified).

  • public - The member is accessible to the world.
  • private - The member is accessible only in the same class it is defined.
  • protected - The member is accessible only in classes defined in the same package or any subclasses thereof.
  • package-private - The member is accessible only to other classes in the same package but not in subclasses. Again, this is the default when no access modifier is specified.

In robotics, using public for everything will work fine. Access modifiers are typically important when creating libraries that will be shared with other projects. In those cases, there may be internal members that should not be exposed to users of the library.

Here is a video about access control. We will discuss access control in more detail in a later lesson.