Declarations
Mughal and Rasmussen cover the Java SE 8 OCA Exam objectives having to do with Declarations.
Programmer I Exam Objectives |
|
[1.2] Define the structure of a Java class |
§3.1, p. 48 |
[4.1] Declare, instantiate, initialize, and use a one-dimensional array |
§3.4, p. 58 |
[4.2] Declare, instantiate, initialize, and use multi-dimensional array |
§3.4, p. 64 |
[6.1] Create methods with arguments and return values; including overloaded methods
|
§3.2, p. 49 §3.5, p. 72 |
[6.3] Create and overload constructors; including impact on default constructors
|
§3.3, p. 53 |
[6.6] Determine the effect upon object references and primitive values when they are passed into methods that change the values
|
§3.5, p. 72 |
[7.4] Use super and this to access objects and constructors
|
§3.2, p. 50 |
Supplementary Objectives |
|
§3.4, p. 68 §3.4, p. 69 |
|
§3.6, p. 81 |
|
§3.7, p. 85 |
|
§3.8, p. 87 |
3.1 Class Declarations
A class declaration introduces a new reference type. For the purpose of this book, we will use the following simplified syntax of a class declaration:
class_modifiers class class_name extends_clause implements_clause // Class header { // Class body field_declarations method_declarations constructor_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:
An accessibility modifier (§4.5, p. 118)
Additional class modifiers (§4.6, p. 120)
Any class it extends (§7.1, p. 264)
Any interfaces it implements (§7.6, p. 290)
The class body, enclosed in braces ({}), can contain member declarations. In this book, we discuss the following two kinds of member declarations:
Field declarations (§2.3, p. 40)
Method declarations (§3.2, p. 49)
Members declared static belong to the class and are called static members. Non-static members belong to the objects of the class and are called instance members. In addition, the following declarations can be included in a class body:
Constructor declarations (§3.3, p. 53)
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 braces ({}), 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, non-static 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 can refer only to other static members.