CHAPTER 2 ■ JAVA SYNTAX
Access Modifiers
Classes, interfaces, fields, and methods all use various access modifiers to indicate which other classes
and interfaces can see and (potentially) modify the item in question. Java has four access modifiers:
private, package-private, protected, and public.
- private means that only the other members (that is, fields and methods) within a
class can see and (for fields) modify the method or field at hand. Private classes
and interfaces appear only within classes, never as stand-alone constructs. - package-private (often just called package) means that other members of the
same package have access to the item. package-private is the default access
modifier and does not have a keyword, because package is used to specify the
package for a class or interface. To declare package access for something, use no
access modifier. - protected indicates that only descendants of the class can access the item. Classes
can be protected, but protected classes generally appear only within other classes
(an idiom called an inner class). Similarly, interfaces can be protected (provided
they are within a class), but it's rare (I've never seen one). protected is most often
used on fields and methods within classes. - public indicates that any object has access to the item. public is often used (and
probably overused quite a bit). It pays to get into the habit of asking whether
anything should be public.
One other thing to know is that the access modifiers are hierarchical. private includes package-
private (that is, if something can see a private object, it can see a package-private object, too), package-
private includes protected, and protected includes public. Hard-to-find problems can arise when
people forget that the access modifiers are hierarchical. Imagine a package with multiple classes and
within that package, some class has a method visible to the package and another class has a protected
method of the same name. Potentially, code can end up calling the wrong method. It doesn't happen
often, but it's tough to figure out when it does.
■ Note Access modifiers can be tricky. In the course of writing this brief description of them, I tripped over all
kinds of uses I hadn't previously considered (it's been a learning experience). For example, Ithought that interfaces
could not be protected. However, they can be protected (or private) when they appear within classes. private and
public are easy to understand and use. For package and protected, think carefully before deciding to use that
modifier.
Interfaces
Interfaces define behaviors that classes must implement if they implement the interface. Interfaces are
always abstract, and all the methods they contain are also always abstract. Abstract (which Java supports
with abstract keyword) means that the class or method or field or whatever cannot be instantiated (that
is, created) where it is defined. Some other object must instantiate the item in question. In the case of