Java Reference
In-Depth Information
decides which method to call based on the type of the argument passed to the
method.
When you are defining a method, the name of the method is always followed by the
method's parameter list, which must be enclosed in parentheses. The parameter list
defines zero or more arguments that are passed to the method. The parameter spec‐
ifications, if there are any, each consist of a type and a name and are separated from
each other by commas (if there are multiple parameters). When a method is
invoked, the argument values it is passed must match the number, type, and order
of the parameters specified in this method signature line. The values passed need
not have exactly the same type as specified in the signature, but they must be con‐
vertible to those types without casting.
When a Java method expects no arguments, its parameter list
is simply () , not (void) . Java does not regard void as a type—
C and C++ programmers in particular should pay heed.
Java allows the programmer to define and invoke methods that accept a variable
number of arguments, using a syntax known colloquially as varargs . Varargs are
covered in detail later in this chapter.
The final part of a method signature is the throws clause, which is used to list the
checked exceptions that a method can throw. Checked exceptions are a category of
exception classes that must be listed in the throws clauses of methods that can
throw them. If a method uses the throw statement to throw a checked exception, or
if it calls some other method that throws a checked exception and does not catch or
handle that exception, the method must declare that it can throw that exception. If a
method can throw one or more checked exceptions, it specifies this by placing the
throws keyword after the argument list and following it by the name of the excep‐
tion class or classes it can throw. If a method does not throw any exceptions, it does
not use the throws keyword. If a method throws more than one type of exception,
separate the names of the exception classes from each other with commas. More on
this in a bit.
Method Modiiers
The modifiers of a method consist of zero or more modifier keywords such as pub
lic , static , or abstract . Here is a list of allowed modifiers and their meanings:
abstract
An abstract method is a specification without an implementation. The curly
braces and Java statements that would normally comprise the body of the
method are replaced with a single semicolon. A class that includes an abstract
method must itself be declared abstract . Such a class is incomplete and cannot
be instantiated (see Chapter 3 ).
Search WWH ::




Custom Search