The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Defining Methods

The next figure shows the code for Stack's push method. This method puts the object argument onto the top of the stack and returns the object.

The push Method and the Structure of a Method Definition

Like a class, a method definition has two major parts: the method declaration and the method body. The method declaration defines all the method's attributes, such as access level, return type, name, and arguments, as shown in the following figure. The method body is where all the action takes place. It contains the instructions that implement the method.

Components of the Declaration of the push Method

The only required elements of a method declaration are the method's name, return type, and a pair of parentheses: ( and ). A method declaration can provide more information about the method, including the return type of the method, the number and type of the arguments required by the method, and which other classes and objects can call the method. The next table shows all possible elements of a method declaration.
Method Declaration Elements
Element Function
accessLevel (Optional) Access level for the method
static (Optional) Declares a class method
abstract (Optional) Indicates that the method is not implemented
final (Optional) Indicates that the method cannot be overridden
native (Optional) Indicates that the method is implemented in another language
synchronized (Optional) The method requires a monitor to run
returnType methodName The method's return type and name
( paramList ) The list of arguments to the method
throws exceptions (Optional) The exceptions thrown by the method
Each element of a method declaration can be further defined and is discussed as indicated in the following list:
accessLevel
As with member variables, you control which other classes have access to a method using one of four access levels: public, protected, package, and private. The section Controlling Access to Members of a Class (in the Learning the Java Language trail) covers access levels in detail.
static
As with member variables, static declares this method as a class method rather than an instance method. The section Understanding Instance and Class Members (in the Learning the Java Language trail) talks about declaring instance and class methods.
abstract
An abstract method has no implementation and must be a member of an abstract class. Refer to the section Writing Abstract Classes and Methods (in the Learning the Java Language trail) for information about why you might want to write an abstract method and how such methods affect subclasses.
final
A final method cannot be overridden by subclasses. The section Writing Final Classes and Methods (in the Learning the Java Language trail) discusses why you might want to write final methods, how they affect subclasses, and whether you might want to write a final class instead.
native
If you have a significant library of functions written in another language, such as C, you may wish to preserve that investment and to use those functions from a program written in the Java programming language. Methods implemented in another language are called native methods and are declared as such using the native keyword. Check out our Java Native Interface (in the Learning the Java Language trail) trail for information about writing native methods.
synchronized
Concurrently running threads often invoke methods that operate on the same data. Mark these methods with the synchronized keyword to ensure that the threads access information in a thread-safe manner. Synchronizing method calls is covered in Threads: Doing Two or More Tasks At Once (in the Learning the Java Language trail). Take particular note of the section Synchronizing Threads (in the Learning the Java Language trail).
returnType
A method must declare the data type of the value that it returns. If your method does not return a value, use the keyword void for the return type. The section Returning a Value from a Method (in the Learning the Java Language trail) talks about the issues related to returning values from a method.
methodName
A method name can be any legal identifier. You need to consider code conventions, name overloading, and method overriding when naming a method. These topics are covered in the next section Naming a Method.
( paramlist )
You pass information into a method through its arguments. See the next section, Passing Information into a Method or a Constructor (in the Learning the Java Language trail).
throws exceptionList
If your method throws any checked exceptions, your method declaration must indicate the type of those exceptions. See Handling Errors with Exceptions (in the Learning the Java Language trail) for information. In particular, refer to Specifying the Exceptions Thrown by a Method (in the Learning the Java Language trail).
Two of these components comprise the method signature: the method's name and the parameter list.

Naming a Method

Although a method name can be any legal identifier, code conventions restrict method names. In general, method names should be verbs and should be in mixed case, with the first letter in lowercase and the first letter of each internal word in uppercase. Here are some examples:
toString
compareTo
isDefined
setX
getX
A method name should not be the same as the class name, because constructors are named for the class. The JavaBeans architecture naming conventions further describe how to name methods for setting and getting properties.

Note:  You should refer to Sun Microsystems' code conventions for the Java programming language (outside of the tutorial) and the JavaBeans architecture naming conventions outlined in the JavaBeans specification (outside of the tutorial).
Typically, a method has a unique name within its class. However, three situations might cause a method to have the same name as other methods in the class or in a superclass: overriding methods, hiding methods, and name overloading.

A method with the same signature and return type as a method in a superclass overrides or hides the superclass method. The section Overriding and Hiding Methods (in the Learning the Java Language trail) describes what each means, shows you how to override and to hide methods, and discusses related issues.

The Java programming language supports name overloading for methods, which means that multiple methods in the same class can share the same name if they have different parameter lists. Suppose that you have a class that can draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. In other languages, you have to think of a new name for each method, for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different type of argument to each method. Thus, the data drawing class might declare three methods named draw, each of which takes a different type of argument.

public class DataArtist {
    ...
    public void draw(String s) {
        ...
    }
    public void draw(int i) {
        ...
    }
    public void draw(float f) {
        ...
    }
}
Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types. You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.