Java Reference
In-Depth Information
Since we have declared the interface as
public
, the constants are also available outside the package
containing the
ConversionFactors
interface. You can access constants defined in an interface in the
same way as for public and static fields in a class - by just qualifying the name with the name of the
interface. For instance, you could write:
public MyClass {
// This class can access any of the constants defined in ConversionFactors
// by qualifying their names...
public static double poundsToGrams(double pounds) {
return pounds*ConversionFactors.POUND
_
TO
_
GRAM;
}
// Plus the rest of the class definition...
}
Since the
ConversionFactors
interface only includes constants, all a class has to do to gain access
to them using their unqualified names is to declare that it implements the interface. For instance, here's
a class that does that:
public class MyOtherClass implements ConversionFactors {
// This class can access any of the constants defined in ConversionFactors
// using their unqualified names, and so can any subclasses of this class...
public static double poundsToGrams(double pounds) {
return pounds*POUND
_
TO
_
GRAM;
}
// Plus the rest of the class definition...
}
The constants defined in the
ConversionFactors
interface are now members of
MyOtherClass
and therefore will be inherited in any derived classes. Let's try a working class that implements
ConversionFactors
.
Try It Out - Implementing an Interface
Here's a simple class that implements the
ConversionFactors
interface:
public class TryConversions implements ConversionFactors {
public static double poundsToGrams(double pounds) {
return pounds*POUND
_
TO
_
GRAM;
}
public static double inchesToMillimeters(double inches) {
return inches*INCH
_
TO
_
MM;
}
public static void main(String args[]) {
int myWeightInPounds = 180;
int myHeightInInches = 75;
System.out.println("My weight in pounds: " +myWeightInPounds +
" \t-in grams: "+ (int)poundsToGrams(myWeightInPounds));