The Four Levels of Access Protection

Any two different Java objects have one of four relations to each other. The four relations are:

These relationships are not mutually exclusive. One object can be a subclass of another object in the same package, for example.

You can define which of your class's members, that is its fields and its methods, are accessible to other objects in each of these four groups, relative to the current class.

If you want any object at all to be able to call a method or change a field, declare it public.

If you want only objects in the same class to be able to get or set the value of a field or invoke a method, declare it private.

If you want access restricted to subclasses and members of the same package, declare it protected.

Finally, to restrict access only to objects in the same package, use no access declaration at all. This is called "package" or "default" access, but it has no keyword. The default keyword means something else entirely.

Can anyone remember what?

By default, all classes you write are in the same package. However, they are in different packages from the Java classes like System or Applet.

The public fields and methods of an object can be accessed from anywhere the object itself can be seen. Anyone can touch an object's public members. They should be kept to a minimum. Public fields should relate very closely to the core functionality of the class. They should not show intimate details of the inner workings of the class. Except in very simple instances fields should probably not be public.

The private fields and methods of an object can only be accessed by the object itself and by other objects of the same class (siblings). An object may touch its sibling's private parts. A sibling is an object in the same class but which is not the same object.

Previous | Next | Top | Cafe au Lait

Copyright 1997-1998 Elliotte Rusty Harold
Last Modified September 25, 1998