Java Reference
In-Depth Information
Figure 5.1
Output of the DateProgram.
Methods in Java can appear only within a class because Java is a strictly
object-oriented programming language. In many languages, methods
appear at a global level and can be invoked at any time. In Java, methods
(not declared as static) can only be invoked on instances of the class. For
example, the getDay() method can be invoked only on instances of the
Date class.
If you do want to write a global-type method that can be invoked by
anyone at any time without requiring an instance of a class, you write a
static method. In Chapter 7, “Advanced Java Language Concepts,” static
methods are discussed. A static method is essentially equivalent to the
concept of a global method.
Method Signature
You can determine everything you need to know about invoking a method by
looking at the method's signature . The signature includes information such as
the method name, the parameter list, and the data type of any return value. For
example, the signature of main() is as follows:
public static void main(String [] args)
Notice that the signature of a method does not include any of the statements
in the body of the method. The signature is the declaration part of the method.
The following list discusses each of the components in a method signature,
shown in the order they appear when declaring a method.
Access specifier. The possible values of the access specifier are public,
private, protected, or default access, which is obtained by leaving off the
access specifier. Public access allows anyone to invoke the method from
anywhere. Private access means that no one else can invoke the method,
thereby hiding it within the class. The protected and default access
apply to inheritance and packages, respectively, and are discussed in
detail in Chapter 7, “Advanced Java Language Concepts.”
Search WWH ::




Custom Search