Java Reference
In-Depth Information
Listing 6-4. Counting Cat objects
class Cat extends Mammal{
static int numberOfCats;
Cat() {
numberOfCats++;
}
}
To get the number of Cat objects, we can either implement a method to return the value or we can
reference the field and get its value. To reference a static member, we use the name of the class
separated from the static member's name by a period, as shown in Listing 6-5.
Listing 6-5 Referencing a static member
System.out.println(Cat.numberOfCats);
However, we should generally prefer the idiom of making the static field private and creating a get
method to return that value. Otherwise, we expose the field for other classes to set, and that is probably a
bug. Listing 6-6 shows the Cat class modified to use the private field pattern (patterns are common
idioms in computer science—there are many of them, and they are a worthwhile thing to study if you
pursue programming).
Listing 6-6. The Cat class with a private static field
class Cat extends Mammal{
private static int numberOfCats;
Cat() {
numberOfCats++;
}
public static final int getNumberOfCats() {
return numberOfCats;
}
}
Do you notice that the method is also static? We need only one such method, regardless of how
many Cat objects we create, so it makes sense for getNumberOfCats to be static. We also make it final ,
because there's no reason for child classes to implement their own getNumberOfCats methods. Thus, if
we have Tiger and Lion classes extending the Cat class, they could not have getNumberOfCats methods
unless those methods have different arguments.
Polymorphism
Polymorphism , from the Greek poly, for many, and morph, for form, means that the same thing can have
different forms. It's a technical term in many fields, including chemistry, biology, and (of course)
Search WWH ::




Custom Search