Examples of class methods
In the same way that a class can provide variables
and constants, a class can also provide useful methods that do not require an object of
the class.
An example of a class method used in previous units
is:
nextGuess
= Math.random();
This example is a method that returns a random value
from 0.0 up to (but not including) 1.0. There is no need for an instance of the Math class
for some other object to use this public static method.
We could define a class method addUp() for a class
Counter, that when provided with an integer returns the total of numbers. For example, if
provided with the number 3, would return (1 + 2 + 3) = 6. Such a class and its public
static method would look as follows:
public
class Counter
{
public static int
addUp( int limit )
{
int total
= 0;
int i = 1;
while( i
<= limit)
{
total += i;
i = i + 1;
}
return total;
}
}
An applet to make use of this class method, without
creating an instance of the class, is as follows:
//
<APPLET code="ClassMethodApplet.class" width=275
height=200></APPLET>
import java.applet.Applet;
import java.awt.*;
public class
ClassMethodApplet extends Applet
{
public void paint
(Graphics g)
{
int x =
20;
int y =
20;
// use
Class method 'addUp()'
int result
= Counter.addUp( 4 );
g.drawString("result = " + result, x, y);
}
}
Notice how there is never an instance of the class
Counter created. The class method is invoked through the sending of
a message to the Counter class itself:
Counter.addUp(
4 )
Back
to top

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg
|