Java Reference
In-Depth Information
In Section 5.13, we discussed class variables. Class methods are conceptually related and use a
related syntax (the keyword static in Java). Just as class variables belong to the class rather
than to an instance, so do class methods.
A class method is defined by adding the keyword static in front of the type name in the
method's signature:
public static int getNumberOfDaysThisMonth()
{
...
}
Such a method can then be called by specifying the name of the class in which it is defined,
before the dot in the usual dot notation. If, for instance, the above method is defined in a class
called Calendar , the following call invokes it:
int days = Calendar.getNumberOfDaysThisMonth();
Note that the name of the class is used before the dot—no object has been created.
Exercise 6.49 Read the class documentation for class Math in the package java.lang .
It contains many static methods. Find the method that computes the maximum of two integer
numbers. What is its signature?
Exercise 6.50 Why do you think the methods in the Math class are static? Could they be
written as instance methods?
Exercise 6.51 Write a test class that has a method to test how long it takes to count from 1
to 100 in a loop. You can use the method currentTimeMillis from class System to help
with the time measurement.
6.15.2
The main method
If we want to start a Java application without BlueJ, we need to use a class method. In BlueJ,
we typically create an object and invoke one of its methods, but without BlueJ an application
starts without any object in existence. Classes are the only things we have initially, so the first
method that can be invoked must be a class method.
The Java definition for starting applications is quite simple: the user specifies the class that should be
started, and the Java system will then invoke a method called main in that class. This method must
have a specific signature. If such a method does not exist in that class, an error is reported. Appendix E
describes the details of this method and the commands needed to start the Java system without BlueJ.
Exercise 6.52 Find out the details of the main method and add such a method to your Game
class. The method should create a Game object and invoke the play method on it. Test the main
method by invoking it from BlueJ. Class methods can be invoked from the class's pop-up menu.
Exercise 6.53 Execute your game without BlueJ.
 
Search WWH ::




Custom Search