A method declaration consists of two parts: the method header and the method body. The method header
consists of an optional set of modifiers, an optional set of type parameters, the method return type, the
signature, and an optional tHRows clause listing the exceptions thrown by the method. The method signature
consists of the method name and the (possibly empty) parameter type list enclosed in parentheses. All
methods must have a return type and signature. Type parameters are used to declare generic methods and are
discussed in Chapter 11. Exceptions and throws clauses are discussed in detail in Chapter 12. The method
body consists of statements enclosed between curly braces.
The method modifiers consist of the following:
- annotations Annotations and annotation types are discussed in Chapter 15.
- access modifiers These were discussed on page 47.
abstract An abstract method is one whose body has not been defined in this classthe body is
specified as a semicolon after the parameter list. A subclass is then responsible for providing a body
for this method. This is discussed in Section 3.7 on page 97.
•
- static This is discussed below.
final A final method cannot be overridden in a subclass. This is discussed in Section 3.6 on page
96.
•
synchronized A synchronized method has additional semantics related to the control of
concurrent threads within a program. This is discussed in Section 14.3 on page 345.
•
- native This is discussed in Section 2.11 on page 74.
strict floating point A method declared strictfp has all floating-point arithmetic evaluated strictly.
If a method is declared within a class declared strictfp, then that method is implicitly declared
strictfp. See Section 9.1.3 on page 203 for details.
•
An abstract method cannot be static, final, synchronized, native, or strict. A native method cannot be strict.
When multiple modifiers are applied to the same method declaration, we recommend using the order listed.
2.6.1. Static Methods
A static method is invoked on behalf of an entire class, not on a specific object instantiated from that class.
Such methods are also known as class methods. A static method might perform a general task for all
objects of the class, such as returning the next available serial number or something of that nature.
A static method can access only static fields and other static methods of the class. This is because
non-static members must be accessed through an object reference, and no object reference is available
within a static methodthere is no this reference.
In this book when we use the term method, we usually mean the non-static kind. When the context makes it
ambiguous, we use the term non-static method to be clear.
Exercise 2.9: Add a static method to Vehicle that returns the highest identification number used thus far.
2.6.2. Method Invocations
Methods are invoked as operations on objects via references using the dot (.) operator:
reference.method(arguments)