4.2 Defining Classes


A class declaration introduces a new reference type. It has the following general syntax:


<class  modifiers>   c lass   <class   name >
                              <extends  clause>  <implements  clause>     // Class header
{ // Class body
          <field  declarations>
          <method  declarations>
          <nested  class  declarations>
          <nested  interface  declarations>
          <constructor  declarations>
          <initializer  blocks>
}

In the class header, the name of the class is preceded by the keyword class . In addition, the class header can specify the following information:

  • scope or accessibility modifier (see Section 4.7, p. 131)

  • additional class modifiers (see Section 4.8, p. 134)

  • any class it extends (see Section 6.1, p. 226)

  • any interfaces it implements (see Section 6.4, p. 251)

The class body can contain member declarations which comprise

  • field declarations (see Section 2.3, p. 31)

  • method declarations (see Section 4.3, p. 112)

  • nested class and interface declarations (see Section 7.1, p. 284)

Members declared static belong to the class and are called static members , and non-static members belong to the objects of the class and are called instance members . In addition, the following can be declared in a class body:

  • constructor declarations (see Section 4.4, p. 117)

  • static and instance initializer blocks (see Section 8.2, p. 331)

The member declarations, constructor declarations and initializer blocks can appear in any order in the class body.

In order to understand what code is legal to declare in a class, we distinguish between static context and non-static context . A static context is defined by static methods, static field initializers, and static initializer blocks. A non-static context is defined by instance methods , constructors, non-static field initializers, and instance initializer blocks. By static code we mean expressions and statements in a static context, and similarly by non-static code we mean expressions and statements in a non-static context. One crucial difference between the two contexts is that static code cannot refer to non-static members.



A Programmer[ap]s Guide to Java Certification
A Programmer[ap]s Guide to Java Certification
ISBN: 201596148
EAN: N/A
Year: 2003
Pages: 284

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net