Java Reference
In-Depth Information
public double hpToWatts (double hp) {
return hp*HP _ TO _ WATT;
}
public double ouncesToGrams(double ounces) {
return ounces*OUNCE _ TO _ GRAM;
}
public double poundsToGrams(double pounds) {
return pounds*POUND _ TO _ GRAM;
}
public double inchesToMillimeters(double inches) {
return inches*INCH _ TO _ MM;
}
public static void main(String args[]) {
int myWeightInPounds = 180;
int myHeightInInches = 75;
TryConversions converter = new TryConversions();
System.out.println("My weight in pounds: " +myWeightInPounds +
" \t-in grams: "+ (int)converter.poundsToGrams(myWeightInPounds));
System.out.println("My height in inches: " + myHeightInInches
+ " \t-in millimeters: "
+ (int)converter.inchesToMillimeters(myHeightInInches));
}
}
Note how the methods we were using in the original definition of the class are now not declared as
static . Since interface methods cannot be declared as static , we cannot make them static in the
class that implements the interface. As the methods are now instance methods, we have to create a
TryConversions object, converter , in order to call them.
You also may have noticed how we have implemented more than one interface in the class. A class can
implement as many interfaces as you like. The names of all the interfaces that are implemented appear
after the implements keyword separated by commas.
Of course, you don't have to implement every method in the interface, but there are some consequences
if you don't.
A Partial Interface Implementation
You can omit the implementation of one or more of the methods from the interface in a class that
implements the interface, but in this case the class inherits some abstract methods from the interface so
we would need to declare the class itself as abstract :
public abstract class MyClass implements Conversions {
// Implementation of two of the methods in the interface
public double inchesToMillimeters(double inches) {
return inches*INCH _ TO _ MM;
Search WWH ::




Custom Search