|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
The Java Lesson 14: Creating and calling custom class methods
|
JavaFAQ Home » Java Lessons by Jon Huhtala

The Java Lesson 14
Creating and calling custom class methods
Custom class methods
-
Can be defined within any class but not within
another method. Methods can not be nested.
-
Are associated with the class itself
and not with an object of the class. This is indicated by the use of the static keyword within the
method's header. No object must exist to call a class method.
-
Have the general syntax
public static
return-type
method-name(arguments) { statements; }
where:
return-type is the data type of the value to be
returned by the method when it completes its processing. This may be any
primitive data type (such as boolean, byte, char, etc..) or the keyword void if the method returns nothing to the
caller. If the method returns an object reference, a class name may be
specified. This will be covered in a later lesson.
method-name is any valid identifier. It should be
meaningful and follow Java coding conventions by beginning with a lower case
letter.
arguments is a list of local variables whose values are
received as parameters from the caller. If the method requires no arguments,
nothing is coded within the parenthesis.
statements are one or more statements that define the
method's processing. In addition to the local variables received as
parameters, other local variables may be declared.
return
expression;
is required where expression is compatible with the
return-type specified in the method header. If the method header
indicates that no value is to be returned (void is specified), a null return statement such as
return;
may be coded. Otherwise, processing will automatically end when
the closing brace of the method is reached.
-
Receive a copy of values passed from the caller. For security
reasons, a class method is never allowed to access the primitive variables of
the calling method (objects are a bit different and will be covered later).
For example, if a class method is defined with the following header:
public static
double extendedPrice(int quantity, double unitPrice)
it expects to receive two parameters. If a calling method has an
int variable named qty and a double variable named price, it can call the extendedPrice method with the
following expression:
extendedPrice(qty, price)
The caller's values of qty and price will automatically be copied and assigned to the method's
local variables named quantity and unitPrice.
When parameters are passed:
-
The match-up is entirely
positional. The first parameter value is copied and assigned to the first
local variable declared in the method header, the second parameter value is
copied and assigned to the second local variable declared in the method
header, etc..
-
Trying to pass too few or too many
parameters will result in a compile error.
-
Variable names are irrelevant.
Even if the same identifier is used in both the calling method and in the
class method, they reference different memory areas.
-
Data types must be compatible and, if necessary, widening
conversions are automatically performed. For example, the extendedPrice method could be
called with a byte and
an int because they can
be widened to the expected int and double.
Creating and calling custom class methods
Custom class methods
-
Can be defined within any class but not within
another method. Methods can not be nested.
-
Are associated with the class itself
and not with an object of the class. This is indicated by the use of the static keyword within the
method's header. No object must exist to call a class method.
-
Have the general syntax
public static
return-type
method-name(arguments) { statements; }
where:
return-type is the data type of the value to be
returned by the method when it completes its processing. This may be any
primitive data type (such as boolean, byte, char, etc..) or the keyword void if the method returns nothing to the
caller. If the method returns an object reference, a class name may be
specified. This will be covered in a later lesson.
method-name is any valid identifier. It should be
meaningful and follow Java coding conventions by beginning with a lower case
letter.
arguments is a list of local variables whose values are
received as parameters from the caller. If the method requires no arguments,
nothing is coded within the parenthesis.
statements are one or more statements that define the
method's processing. In addition to the local variables received as
parameters, other local variables may be declared.
return
expression;
is required where expression is compatible with the
return-type specified in the method header. If the method header
indicates that no value is to be returned (void is specified), a null return statement such as
return;
may be coded. Otherwise, processing will automatically end when
the closing brace of the method is reached.
-
Receive a copy of values passed from the caller. For security
reasons, a class method is never allowed to access the primitive variables of
the calling method (objects are a bit different and will be covered later).
For example, if a class method is defined with the following header:
public static
double extendedPrice(int quantity, double unitPrice)
it expects to receive two parameters. If a calling method has an
int variable named qty and a double variable named price, it can call the extendedPrice method with the
following expression:
extendedPrice(qty, price)
The caller's values of qty and price will automatically be copied and assigned to the method's
local variables named quantity and unitPrice.
When parameters are passed:
-
The match-up is entirely
positional. The first parameter value is copied and assigned to the first
local variable declared in the method header, the second parameter value is
copied and assigned to the second local variable declared in the method
header, etc..
-
Trying to pass too few or too many
parameters will result in a compile error.
-
Variable names are irrelevant.
Even if the same identifier is used in both the calling method and in the
class method, they reference different memory areas.
-
Data types must be compatible and, if necessary, widening
conversions are automatically performed. For example, the extendedPrice method could be
called with a byte and
an int because they can
be widened to the expected int and double.
Sample program
The following sample program performs temperature conversions using a class
method named convertTemp
which is called from the application's main() method:
public class App {
public static void main(String[] args) {
//
Variables.
double oldTemp;
char scale; double newTemp; char
again;
// Loop to process one temperature
conversion.
do
{
// Get data from the
user.
Utility.separator(50,
'>'); System.out.print("Enter
temperature: "); oldTemp =
Keyboard.readDouble();
System.out.print("Current scale? (C/F): ");
scale = Keyboard.readChar();
// Process
the conversion request.
Utility.skip(); switch (scale)
{
// Cases for a valid
scale.
case
'C': case
'c': case
'F': case
'f': newTemp =
convertTemp(oldTemp,
scale);
System.out.println(" Converted temperature: "
+
Utility.fixedFormat(newTemp,
2));
break;
// Default case for
an invalid scale.
default:
System.out.println(" Invalid
scale");
break;
}
// Ask if they want to do another and
repeat as requested.
Utility.skip(); System.out.print("Again?
(Y/N): "); again =
Keyboard.readChar(); } while (again == 'Y' || again ==
'y'); }
// Class method to convert a temperature from
either centigrade to // fahrenheit or fahrenheit to
centigrade.
public static double convertTemp(double temperature,
char scale) {
// If the scale is centigrade, convert
the temperature to // fahrenheit. Otherwise, convert it
to centigrade.
if (scale == 'C' || scale == 'c')
{ return ((9 * temperature) / 5) +
32; } else
{ return (5 * (temperature -32)) /
9; } } }
Notes:
-
The convertTemp() method expects to receive two parameters. The
first must be a double
(or able to be widened to a double) that represents the temperature to be converted. The
second must be a char
that represents the scale of the temperature to be converted.
-
Because the convertTemp() method is defined within the same
class as the main()
method, it can be called without specifying its class name. Alternatively,
App.convertTemp() could
have been called.
-
The convertTemp() method returns a double so it can be called anywhere a double makes sense. That is
why it can be assigned to the double variable newTemp.
-
Because convertTemp() is public, it may be called from any other class.
That means no one else in the history of mankind will ever have to write
another temperature conversion method as long as they can call App.convertTemp().
Lab exercise for Ferris
students
E-mail your answers to this
assignment no later than
the due date listed in the class schedule.
Review questions
-
Which one statement is true
about the application shown below? The line numbers are for reference purposes
only.
1 2 3 4 5 6 7 8 9 10 |
public
class App { public static void main(String[] args)
{ int length = 5; int
width = 3; System.out.println("Area is " +
area(length, width)); } public static double
area(double len, double wid) { return len *
wid; } } |
-
a compile error will occur
at line 5
-
a compile error will occur
at line 7
-
a compile error will occur
at line 8
-
the program will compile
but an error will occur at run time
-
the program will compile
and run to display "Area is 15.0"
-
Which one statement is true
about the application shown below? The line numbers are for reference purposes
only.
1 2 3 4 5 6 7 8 9 10 |
public
class App { public static void main(String[] args)
{ int hours = 5; double
rate = 7.25; System.out.println("Gross pay: " +
grossPay()); } public static double grossPay()
{ return hours * rate;
} } |
-
a compile error will occur
at line 5
-
a compile error will occur
at line 7
-
a compile error will occur
at line 8
-
the program will compile
but an error will occur at run time
-
the program will compile
and run to display "Gross pay: 36.25"
-
Which one statement is true
about the application shown below? The line numbers are for reference purposes
only.
1 2 3 4 5 6 7 8 9 10 |
public
class App { public static void main(String[] args)
{ int hours = 5; double
rate = 7.25; System.out.println("Gross pay: " +
grossPay(rate, hours)); } public static double
grossPay(int hours, double rate) { return hours
* rate; } } |
-
a compile error will occur
at line 5
-
a compile error will occur
at line 7
-
a compile error will occur
at line 8
-
the program will compile
but an error will occur at run time
-
the program will compile
and run to display "Gross pay: 36.25"
-
Which one statement is true
about the application shown below? The line numbers are for reference purposes
only.
1 2 3 4 5 6 7 8 9 10 |
public
class App { public static void main(String[] args)
{ int hours = 5; double
rate = 7.25; System.out.println("Gross pay: " +
grossPay(hours, rate)); } public static double
grossPay(int hours, double rate) { double gross
= hours * rate; } } |
-
a compile error will occur
at line 5
-
a compile error will occur
at line 8
-
a compile error will occur
at line 9
-
the program will compile
but an error will occur at run time
-
the program will compile
and run to display "Gross pay: 36.25"
Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|
|
|