Java Reference
In-Depth Information
20
21
//call methods
22
dollars = getSales () ;
23
}
24
25
//The getSales() method asks the user to input a dollar amount and validates it.
26
public static double getSales ()
27
{
28
//declare method variables
29
double sales = 0.0;
30
31
String answer = JOptionPane.showInputDialog ( null ,
"Enter the sales amount\n(do not use commas or dollar signs)\n or click Cancel to
exit:" ) ;
32
33
sales = Double .parseDouble ( answer ) ;
34
35
return sales;
36
}
37 }
FIGURE 4-8
When a call statement is encountered, the Java compiler looks for a
matching method, either a method from an imported package, a method
embedded in the application, or a method from an external class. If the call is
not accessing a Java-supplied method, the programmer then must write the
method header and the section of code statements that define the method.
Coding a Method
When coding a new user-defined method, start the code with the method
header. Recall that the method header includes any modifiers, the return value
data type or void, the method name, and any parameters in parentheses.
The beginning code for the getSales() method is shown in lines 25 through
36 in Figure 4-8. The purpose of the getSales() method is to receive a valid sales
amount and return it to the main() method to be stored in the variable location,
dollars. The method header in line 26 contains an access modifier, a method
modifier, and the data type of the return value. These three keywords display
before the name of the method, getSales(). Recall that an access modifier speci-
fies the circumstances in which the class can be accessed. The access modifier,
public, indicates that the method can be accessed by all objects and can be
extended, or used, as a basis for another class. The method modifier enables you
to set properties for the method, such as where it will be visible and how sub-
classes of the current class will interact with the method. The method modifier,
static , indicates that the getSales() method is unique and can be invoked without
creating a subclass or instance.
When a method returns a value, the data type of the return value is the third
keyword listed before the method name. In this case, the getSales() method
returns a double value. Return value identifiers must be declared in the body of
the method, as shown in line 29.
After the return data type, the method header then contains the name of
the method, getSales. In this program, the method header accepts no passed
parameters, so the call statement has no arguments in the parentheses.
Search WWH ::




Custom Search