Access Modifiers in Java - dummies

By Barry Burd

Object-oriented programming like Java is big on hiding details. Programmers who write one piece of code shouldn’t tinker with the details inside another programmer’s code. It’s not a matter of security and secrecy. It’s a matter of modularity.

When you hide details, you keep the intricacies inside one piece of code from being twisted and broken by another piece of code. Your code comes in nice, discrete, manageable lumps. You keep complexity to a minimum. You make fewer mistakes. You save money. You help promote world peace.

You can find plenty of examples of the use of private fields. When a field is declared private, it’s hidden from all outside meddling. This hiding enhances modularity, minimizes complexity, and so on.

Elsewhere are examples of things that are declared public. Just like a public celebrity, a field that’s declared public is left wide open. Plenty of people probably know what kind of toothpaste Elvis used, and any programmer can reference a public field, even a field that’s not named Elvis.

In Java, the words public and private are called access modifiers. No doubt you’ve seen fields and methods without access modifiers in their declarations. A method or field of this kind is said to have default access. Many examples use default access without making a big fuss about it. That’s okay sometimes.

And you can find out about yet another access modifier. It’s the protected access modifier. In Java, the default access for a member of a class is package-wide access. A member declared without the word public, private, or protected in front of it is accessible in the package in which its class resides.

The names of packages, with all their dots and subparts, can be slightly misleading. For instance, when you write a program that responds to button clicks, you normally import classes from two separate packages. On one line, you may have import java.awt.*;. On another line, you may have import java.awt.event.*;. Importing all classes from the java.awt package doesn’t automatically import classes from the java.awt.event package.