Methods 3 - Defining a static method
- Show how to define a method.
- Explain parts of method header.
- Term: formal parameter = variable in method which gets the argument value.
- Syntax of method header
Method header syntax
A method header is the part of the method definition that occurs at the beginning. The following definition leaves out a few obscure features, but gives the syntax of ordinary method headers.
See Syntax Notation to understand how to read the following.
methodHeader | = | [visibility] ["static "] returnType methodName "(" [parameterList] ")" . |
visibility | = | "public " | "private " | "protected " . |
parameterList | = | parameterDeclaration {"," parameterList} . |
parameterDeclaration | = | type ParameterName . |
returnType | = | "void" | type |
How to define your own method
The previous program is rewritten below to define a method to convert from kilometers to miles.
The method call, and the first line (header) of the method definition are highlighted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// File : methods/KmToMilesMethod.java // Purpose: Convert kilometers to miles using a method. JOptionPane IO. // Highlight call and method definition header. // Author : Fred Swartz // Date : 22 Apr 2006 import javax.swing.*; public class KmToMilesMethod { //============================================================ constants private static final double MILES_PER_KILOMETER = 0.621; //================================================================= main public static void main(String[] args) { //... Local variables String kmStr; // String km before conversion to double. double km; // Number of kilometers. double mi; // Number of miles. //... Input kmStr = JOptionPane.showInputDialog(null, "Enter kilometers."); km = Double.parseDouble(kmStr); //... Computation mi = convertKmToMi(km); //Note 1 //... Output JOptionPane.showMessageDialog(null, km + " kilometers is " + mi + " miles."); } //========================================================= convertKmToMi private static double convertKmToMi(double kilometers) { //Note 2 double miles = kilometers * MILES_PER_KILOMETER; return miles; } } |
Notes
- Call our own method below to do the conversion. We could have qualified the name with our class name, KmToMilesMethod.convertKmToMi(km), but this is unnecessary when calling a static method in the same class.
- Altho this method is trivial, just a multiplication, it is good practice to separate the "model", or "logic", from the user interface. As programs become larger, this separation becomes essential.
Anatomy of the convertKmToMi
method header
We'll take a look at each of the parts of the method header in order.
- Visibility -
public
,private
, or package -
private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; }
For greatest reliability and flexibility in your programs, you should always give methods the lowest visibility to others that you can.
When you define a method, you should think about who can use it. Generally you want to choose the lowest level of visibility that makes your program usable, either
private
or the default (package). Here are the four options, from least visible to most visible.private
- If you don't want any other class to use it, declare it private. This is a good choice.- None (package) - If you don't specify anything, the default visibility allows
only classes in the same package (directory) to
see it. This is a common choice. It's common to use
public
visibility when package visibility is more appropriate -- I do it myself. The lack of a keyword for package visibility makes it a little harder to read. protected
- Don't use thisprotected
, except in certain cases to let a child class see it. Even then, its use is controversial.public
- Let's anyone see it. Choose this if you've defined a method that will be used by others outside of your project. Note thatmain
must be declaredpublic
so the run-time system can call it.
- Class (static) or instance method
-
private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; }
A method should be declared
static
if it doesn't user instance variables or methods. A static method must use only only parameters, local variables, and static constants, and other static methods in the same class. If thestatic
keyword is omitted, the method will be an instance method. This example uses static, but soon you will learn about instance methods too. - Return type
-
private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; }
- Method name
-
private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; }
Method names should begin with a lowercase letter. Method names are typically verbs, whereas variable names are usually nouns.
- Parameter(s)
-
private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; }
Parameters are enclosed in parentheses following the method name. They are also called formal parameters). There is only one parameter in this example -
kilometers
, but if there are more, they must be separated by commas. The type of each parameter is specified before the name (eg,double
). Parameters are local variables that only exist inside the method. They are assigned initial values from the arguments when the method is called. - Method body
-
private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; }
The body of a method is the statements which are executed when the method is called are enclosed in braces following the the method header. Additional local variables may be defined (eg,
miles
). - Return statement
-
private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; }
A method returns to the caller after it has done what it wants. If the method returns a value (not a void method), it must contain a
return
statement that specifies a value to return. When execution reaches thereturn
statement, control transfers back to the calling method, passing a return value to it. - Returning an expression
-
The above example returns the value in the local variable miles. The return statement can be followed by any expression of the appropriate type, not just a single value. For example, this method body could have been written as a single return statement.
private static double convertKmToMi(double kilometers) { return kilometers * MILES_PER_KILOMETER; }
Order of method definitions doesn't matter
If you define multiple methods in a class, you don't have to worry about the order of the definitions, unlike some other languages.
Review Questions
[TODO]