Java Reference
In-Depth Information
Here are some example method definitions, which begin with the signature and are
followed by the method body:
// This method is passed an array of strings and has no return value.
// All Java programs have an entry point with this name and signature.
public static void main ( String [] args ) {
if ( args . length > 0 ) System . out . println ( "Hello " + args [ 0 ]);
else System . out . println ( "Hello world" );
}
a x
// This method is passed two double arguments and returns a double.
static double distanceFromOrigin ( double x , double y ) {
return Math . sqrt ( x * x + y * y );
}
// This method is abstract which means it has no body.
// Note that it may throw exceptions when invoked.
protected abstract String readText ( File f , String encoding )
throws FileNotFoundException , UnsupportedEncodingException ;
modifiers is zero or more special modifier keywords, separated from each other by
spaces. A method might be declared with the public and static modifiers, for
example. The allowed modifiers and their meanings are described in the next sec‐
tion.
The type in a method signature specifies the return type of the method. If the
method does not return a value, type must be void . If a method is declared with a
non- void return type, it must include a return statement that returns a value of (or
convertible to) the declared type.
A constructor is a block of code, similar to a method, that is used to initialize newly
created objects. As we'll see in Chapter 3 , constructors are defined in a very similar
way to methods, except that their signatures do not include this type specification.
The name of a method follows the specification of its modifiers and type. Method
names, like variable names, are Java identifiers and, like all Java identifiers, may
contain letters in any language represented by the Unicode character set. It is legal,
and often quite useful, to define more than one method with the same name, as
long as each version of the method has a different parameter list. Defining multiple
methods with the same name is called method overloading .
Unlike some other languages, Java does not have anonymous
methods. Instead, Java 8 introduces lambda expressions,
which are similar to anonymous methods, but which the Java
runtime automatically converts to a suitable named method—
see “Lambda Expressions” on page 76 for more details.
For example, the System.out.println() method we've seen already is an overloa‐
ded method. One method by this name prints a string and other methods by the
same name print the values of the various primitive types. The Java compiler
Search WWH ::




Custom Search