Java Reference
In-Depth Information
System.out.println("My height in inches: " +myHeightInInches +
" \t-in millimeters: "+ (int)inchesToMillimeters(myHeightInInches));
}
}
Compile this with the interface definition in the same directory. When you execute it, you should see
the output:
My weight in pounds: 180 -in grams: 81646
My height in inches: 75
-in millimeters: 1905
How It Works
The fact that we have only used static methods to access the constants from the interface is unimportant - 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 interface.
You can see that we can use the unqualified names for the constants defined in the interface. You could
delete the implements ConversionFactors bit from the first line, and confirm that it still works if
you add the interface name as a qualifier to the references to POUND _ TO _ GRAM and INCH _ TO _ MM .
Interfaces Declaring Methods
You might also want to define an interface declaring the methods to be used for conversions:
public interface Conversions {
double inchesToMillimeters (double inches);
double ouncesToGrams(double ounces);
double poundsToGrams(double pounds);
double hpToWatts(double hp);
double wattsToHP(double watts);
}
This interface declares five methods to perform conversions. Every method declared in the interface
should have a definition within the class that implements it if you are going to create objects of the class.
Since 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 will 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 .
If we want to make use of this interface in the previous example as well as the ConversionFactors
interface, we could redefine the TryConversions class as:
public class TryConversions implements ConversionFactors, Conversions {
public double wattsToHP (double watts) {
return watts*WATT _ TO _ HP;
}
Search WWH ::




Custom Search