Class Declarations – Declarations

3.1 Class Declarations

A class declaration introduces a new reference type and has the following syntax:

Click here to view code image

class_modifiers
 class
class_name extends_clause implements_clause
 // Class header
{ // Class body
field_declarations
method_declarations
constructor_declarations
member_type_declarations
}

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:

  • The following class modifiers:

Image Access modifiers: public, protected, private (§6.5, p. 345)

Image Non-access class modifiers: abstract (§5.4, p. 218), final (§5.5, p. 225), static (§9.2, p. 495), sealed and non-sealed (§5.15, p. 311)

  • Any class it extends using the extends clause (§5.1, p. 191)
  • Any interfaces it implements using the implements clause (§5.6, p. 237)

The class body, enclosed in curly brackets ({}), can contain member declarations, which comprise the following:

The declarations can appear in any order in the class body. The only mandatory parts of the class declaration syntax are the keyword class, the class name, and the class body curly brackets ({}), as exemplified by the following class declaration:

class X { }

To understand which code can be legally declared 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, instance field initializers, instance initializer blocks, and constructors. By static code, we mean expressions and statements in a static context; 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 in a class can only refer to other static members in the class, whereas non-static code can refer to any member of the class.