Java Reference
In-Depth Information
The fact that you have used only static methods to access the constants from the utility class is unimport-
ant — it's just to keep the example simple. They are equally accessible from instance methods in a class.
The two conversion methods use the conversion factors defined in the ConversionFactors class. Be-
cause you have imported the static fields from the ConversionFactors class in the conversions pack-
age into the TryConversions.java source file, you can use the unqualified names to refer to the con-
stants.
Interfaces Declaring Methods
The primary use for an interface is to define the external form of a set of methods that represent a particular
functionality. Let's consider an example. Suppose that you want to specify a set of methods to be used for
conversions between metric and imperial measurements. You could define such an interface like this:
public interface Conversions {
double inchesToMillimeters (double inches);
double ouncesToGrams(double ounces);
double poundsToGrams(double pounds);
double hpToWatts(double hp);
double wattsToHP(double watts);
}
Directory "TryConversions2"
This interface declares five methods to perform conversions. Every method that is declared in the inter-
face must have a definition within a class that implements the interface if you are going to create objects of
the class type. A class that implements this interface would look like this:
public class MyClass implements Conversions {
// Implementations for the methods in the Conversions interface
// Definitions for the other class members...
}
Because the methods in an interface are, by definition, public, you must use the public keyword when
you define them in your class — otherwise, your code does not compile. The implementation of an interface
method in a class must not have an access specifier that is more restrictive than that implicit in the abstract
method declaration, and you can't get less restrictive than public .
A class can implement more than one interface. In this case, you write the names of all the interfaces that
the class implements separated by commas following the implements keyword. Here's an example:
public class MyClass implements Conversions, Definitions, Detections {
// Definition of the class including implementation of interface methods
}
Search WWH ::




Custom Search