Scoping in Java
Home Up Search Java 2 API C++ Resources

Click here for a more general discussion of scoping.

In Java, scoping is designated by a keyword preceding a class, property or method definition.  

 There are 5 scoping levels in Java:

  1. Local :  variables can be used in anything within the nearest enclosing curly braces.    No keyword needed.
  2. Private: Properties and methods can be used only by members of this exact class. 
  3. Protected:   Properties and methods can be used by any member of this class or its subclasses.
  4. Package:  Any classes within the package can use this class and any non-private or local properties and methods.  No keyword needed. 
  5. Public : Classes, properties or methods are available for use and modification by any object.

Examples:

A public class:

public class MyJunk
{
    .....
}

A package visible method:

JComponent makeWindow(Rectangle bounds){   
    .....
}

A protected method:

protected void setState(AState aState)
{
    ....
}

A private property:

private double answer = 0.0;

A local variable:

int calcIt()
{
    LRStruct list = new LRStruct();  // list is scoped only to this method.
    .....
}

The following is not an example of good programming practice!

void doItAll( int x)    // x is scoped only to this method.
{
    if(x>0)  // x is whatever was passed to the method.
    {
         int x = 3;  // this x is scoped only to the if{...} block
         ......  // x is always 3 here.
    }
    .....  // x is whatever was passed to the method.

}