Java Reference
In-Depth Information
following code shows an interface extending two interfaces at once using a comma
in the extends clause:
public interface A {...}
public interface B {...}
public interface C extends A, B {...}
An interface can also contain data fields, and those fields can be seen by
implementing classes. Any data fields in an interface are implicitly static and
final though those qualifiers need not appear. Thus data fields in interfaces are
effectively constants and, by convention, are best declared using all uppercase
characters.
Placing constants in an interface is a common, though not recommended,
practice. As an illustration of the convenience of this technique, consider the
MyConstants interface shown here:
public interface MyConstants {
final static double G = 9.8;
final static double C = 2.99792458e10;
}
The following Calculations class implements MyConstants and so can
refer to the constants directly:
class Calculations implements MyConstants {
// Can directly use the constants defined
// in the MyConstants interface
public double calc (double t) {
double y = 0.5*G*t*t;
return y;
}
}
If we instead made MyConstants a class, we would need to reference the
constants with a class name prefix as follows:
double y = 0.5 * MyConstants.G*t*t;
This obviously becomes awkward if you have a long equation with lots of con-
stants taken from other classes.
However, despite its usefulness, using an interface just to hold constants is not
recommended since it really is an abuse of the interface concept. An interface full
Search WWH ::




Custom Search