Untitled Document
Untitled Document


  • One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access specifiers.

  • Java offers four access specifiers, listed below in decreasing accessibility:

  • public:

    1. public classes, methods, and fields can be accessed from everywhere.

    2. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename.

    3. You use public classes, methods, or fields only if you explicitly want to offer access to these entities and if this access cannot do any harm. An example of a square determined by the position of its upper-left corner and its size:


    1. protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package, but not from anywhere else.

    2. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes.


    1. If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.

    2. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package.


    Welcome java