Page 383 - Introduction to Programming with Java: A Problem Solving Approach
P. 383
9.3 Class Methods
Class methods, like class variables, relate to the class as a whole, and they don’t relate to individual objects. As such, if you need to perform a task that involves the class as a whole, then you should implement and use a class method. In Chapter 5 you used class methods defined in the Java API Math class; for example, Math.round and Math.sqrt. Now you’ll learn how to write your own class methods. Class methods often access class variables, and in writing your own class methods, you’ll get an opportunity to see how to access class variables that you’ve defined.
Class Method Syntax
See Figure 9.2’s Mouse4 class. In particular, look at the printMouseCount method. It deals with class- wide information, so it’s appropriate to make it a class method. More specifically, it prints the value of mouseCount, where mouseCount is a class variable that keeps track of the total number of mouse objects.
9.3 Class Methods 349
public class Mouse4
{
private static int mouseCount; ⎫⎬ private static Mouse4 youngestMouse;⎭ private int age;
class variables
Apago PDF Enhancer
Mouse4.mouseCount++;
Mouse4.youngestMouse = this;
specifies a class method
public Mouse4()
{
}
public static void printMouseCount()
{
}
}
// end class Mouse4
{
}
{
}
Mouse4 pinky = new Mouse4();
pinky.olderByOneDay();
Mouse4.printMouseCount();
System.out.println("Total mice = " + Mouse4.mouseCount);
public void olderByOneDay()
this.age++;
//*******************************************************
public static void main(String[] args)
Normally, to access a class variable, prefix it with <class-name> dot.
Normally, to access a class method, prefix it with <class-name> dot.
Figure 9.2 A simple mouse program that illustrates class member concepts