Java Reference
In-Depth Information
// now for the Cat method
lookupCat(new String[] {"Breed", "Burmese", "Coat", "Silky"});
// or
String[] criteria = {" Breed", "Burmese", "Coat", "Silky"};
lookupCat(criteria);
}
The code to use the
lookupDog
method is much easier to read, write, and maintain than
the equivalent
lookupCat
method.
Static Imports
Prior to JDK 5 some programmers were defining constants in interfaces, as this allowed them
to
implement
the interface, giving them a shorthand way of writing the constant name. This is
shown in the following example:
public interface BadInterface {
public static final int FIRST_NAME_POSITION = 1;
}
public class BadClass implements BadInterface {
public static void main(String[] args) {
System.out.println("First name = " + args[FIRST_NAME_POSITION]);
}
}
There are a couple of problems with this:
•
A class that implements an interface is said to “be” an instance of that interface. If you
have a reasonable name for your interface, it probably doesn't make sense to say your
class “is” an instance of it.
•
If your class implements an interface, then any subclasses of your class will also imple-
ment the interface. Effectively, the constants will become part of the namespace of the
subclass—even though the subclass may have no need of these constants.
To get around these problems, JDK 5 introduces the idea of
static imports
—the ability to
import the static members from another class or interface.
For instance, if you were using the logging features (discussed in the section “Logging”
later in this chapter), you would normally have to qualify the logging levels as this code
snippet shows:
myLogger.log(Level.FINE, "This message is at FINE level");
However, static imports allow us to refer to the static object
FINE
as though it had been
defined within our own class:
import static java.util.logging.Level.*;
// ...
myLogger.log(FINE, "This message is at FINE level");