Java Reference
In-Depth Information
Save the file in a new directory, TryConversions2 , and add a source file containing the definition for the
Conversions interface to the same directory. You name a file containing an interface definition in a sim-
ilar way to that of a class — the file name should be the same as the interface name, with the extension
.java . Thus, the source file containing the Conversions interface definition is Conversions.java .
How It Works
The methods you were using in the original definition of the class are now not declared as static . Be-
cause interface methods are by definition instance methods, you cannot declare them as static in the class
that implements the interface. As the methods are now instance methods, you have to create a TryCon-
versions object, converter , to call them.
Of course, in this instance, statically importing the constants that are used by the interface method im-
plementations is a clumsy way of doing things. Because the constants are clearly related to the methods,
it would probably be better to define all the constants in the Conversions interface in addition to the
method declarations.
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 an interface in a class that implements
the interface, but in this case the class inherits some abstract methods from the interface so you would need
to declare the class itself as abstract :
import static conversions.ConversionFactors.INCH_TO_MM;
import static conversions.ConversionFactors.OUNCE_TO_GRAM;
public abstract class MyClass implements Conversions {
// Implementation of two of the methods in the interface
@Override public double inchesToMillimeters(double inches) {
return inches*INCH_TO_MM;
}
@Override public double ouncesToGrams(double ounces) {
return ounces*OUNCE_TO_GRAM;
}
// Definition of the rest of the class...
}
You cannot create objects of type MyClass . To arrive at a useful class, you must define a subclass of
MyClass that implements the remaining methods in the interface. The declaration of the class as abstract
is mandatory when you don't implement all of the methods that are declared in an interface. The compiler
complains if you forget to do this.
Note the use of the @Override annotation. For a class that implements an interface and is not abstract,
there is no need to use the @Override annotation because the compiler always generates an error message
if you fail to implement any interface method with the correct signature. However, if you want to use the
annotation in this case, you are free to do so. When you declare a class as abstract , no error message is pro-
duced for an incorrect signature for an interface method because the compiler has no way to know what you
Search WWH ::




Custom Search