Every member of a class, be it a field or a method, has an access control attribute which affects the manner in which that member can be accessed. The members of a class can be private, public or protected. For example, the fields real and imag declared in Program are both private. Private members can be used only by methods of the class in which the member is declared.
On the other hand, public members of a class can be used by any method in any class. All of the methods defined in Programs , , and all declared to be public.
In effect, the public part of a class defines the interface to that class and the private part of the class encapsulates the implementation of that class. By making the implementation of a class private, we ensure that the code which uses the class depends only on the interface and not on the implementation of the class. Furthermore, we can modify the implementation of the class without affecting the code of the user of that class.
Protected members are similar to private members. That is, they can be used by methods of the class in which the member is declared. In addition, protected members can also be used by methods of all the classes derived from the class in which the member is declared. The protected category is discussed again in Section .
Java introduces the notion of a package . A Java package is a collection of related classes. Unless declared otherwise, the members of a class are accessible only by the methods of classes in the same package. In this text, we do not use packages explicitly. For convenience, you should consider all the classes discussed in this book to be elements of the same package.