Java Reference
In-Depth Information
Declaring Methods
A Java class contains fi elds that represent the attributes of the object and methods that
represent the behaviors of the object. We have already discussed fi elds in detail. The exam
objectives state that you should be able to “develop code that declares both static and non-
static methods, and — if appropriate — use method names that adhere to the JavaBeans
naming standards. Also develop code that declares and uses a variable-length argument
list.” This section discusses everything you need to know about declaring and using Java
methods, including the JavaBeans naming convention, static methods, variable-length
arguments, method overloading, method overriding, and covariant return types.
Method Declarations
The defi nition of a method in Java is referred to as a method declaration . A method
declaration in Java has the following syntax:
accessspecifier otherspecifier returnvalue methodName(parameterlist) throws
exceptionlist {
methodbody
}
Figure 2.9 shows the elements of the sleep method declared in the Thread class.
FIGURE 2.9
The elements that comprise a method declaration.
Access
specifiers
Other
specifiers
Return type
(required)
Method
name
List of parameters
(separated by commas)
public static void sleep(long millis, int nanos) throws InterruptedException {
// The method body goes here
}
Optional list of exceptions
(separated by commas)
Parentheses are required here.
“throws” appears
only with an
exception list.
Like any member of a class, a method has an access specifi er, which is one of the
following four values:
public The method is accessible to any other class.
private The method is only accessible from within the class.
protected Only classes in the same package and child classes can access the method.
Default access Only classes in the same package can access the method.
 
Search WWH ::




Custom Search