Public, Protected, and Private Access

Both attributes and methods can have three different levels of access to them. If they are declared public means objects of any classes have access to them, protected means only objects of classes in the same package have access to them, and private they can only be accessed from within the same class.

Usually we keep attributes private. In order for them to be changed or accessed from other classes, get and set methods are to be used. In this way (with Object Oriented Programming languages such as Java) the creator of the class can determine how the attributes can be worked with.

Usually we make methods intended to be used by other classes public. Though if those methods are only intended to be worked with within a given package, it is better to make the access protected.

Sometimes we will have "helper" methods which are used only within a certain class to help other methods, in which case we make these helper methods private.

- Note that if you are going to have your methods protected, you need to put the package statement at the beginning of each class.



A package is a folder in which Java classes which work with each other are placed. Big projects will have many packages and sub-packages. The package statement helps guide classes to other classes which they will use. For our limited projects, it is not always necessary to declare the name of the package, but doing so assures that the classes can find each other. The line has to be written before the beginning of the class, and is simply the Java reserved word package followed by the package name. For example:

package mypackagename

(Note the convention of having all small letters for even a multiple word package.)


Note in the diagram above that when accessing available things via dot notation, not only do the public methods of other classes in the project, and the protected methods from the same package, but there are a bunch of other methods that show as well. These are the methods which are public and from classes which are inherited by the class. And since all classes inherit the Object class, these above are indeed the Object class' public methods.