private keyword

Method syntax

>>-private-+--------+-+-------+-+--------------+-+--------+->
           '-static-' '-final-' '-synchronized-' '-native-'

>-ResultType-Identifier-(-+---------------------+-)->
                          '-FormalParameterList-'

>-+----------------------+-MethodBody-><
  '-throws-ClassTypeList-'

Field syntax

>>-private-+----------+-+--------+-+-----------+-Type->
           +-final----+ '-static-' '-transient-' 
           '-volatile-'

>-+-Identifier--------------+-+------------------------+-;-><
  |                 v-----' | '-=-+-Expression-------+-'
  '-ArrayIdentifier-+-[-]-+-'     '-ArrayInitializer-'

Description
A private class member or constructor is accessible only within the class body in which the member is declared and is not inherited by subclasses. A class type should be declared abstract only if you intend to complete the implementation by creating subclasses. If you simply intend to prevent instantiation of a class, the proper way to express this is to declare a constructor of no arguments, make it private, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables.

The class java.lang.Math is an example of a class that cannot be instantiated; its declaration looks like this:

public final class Math {
    private Math() { }         // never instantiate this class

    . . . declarations of class variables and methods . . .
}

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

Example
In the following example the private members ID, masterID, and setMasterID may be used only within the body of class Point:

class Point {
    private int ID;
    private static int masterID = 0;
    private void setMasterID() { ID = masterID++; }
    int x, y;

    Point() { setMasterID(); }
}

They may not be accessed by qualified names, field access expressions, or method invocation expressions outside the body of the declaration of Point.

ngrelr.gif (548 bytes)
Syntax diagrams
Access control
abstract keyword
class keyword
final keyword
native keyword
private keyword
protected keyword
public keyword
static keyword
transient keyword
volatile keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.