Java Reference
In-Depth Information
}
The ConversionFactors interface defines five constants for conversions of various kinds. Constants
defined in an interface are automatically public , static , and final. You have no choice about this —
constants defined in an interface always have these attributes. Because the constants are static and final, you
must always supply initializing values for constants defined in an interface. The names given to these in the
ConversionFactors interface use capital letters to indicate that they are final and cannot be altered — this
is a common convention in Java. You can define the value of one constant in terms of a preceding constant,
as in the definition of WATT_TO_HP . If you try to use a constant that is defined later in the interface — if, for
example, the definition for WATT_TO_HP appeared first — your code does not compile.
Because you 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 example, you could write:
public class 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...
}
Because the ConversionFactors interface includes only constants, a class can gain access to them using
their unqualified names by declaring that it implements the interface. This has been the technique employed
in the past. For example, here's a class that implements the ConversionFactors interface:
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 are inherited in any derived classes.
Although this technique of using an interface as a container for constants works and has been widely used
in the past, using a class to contain the constants as static fields and then importing the names of the fields as
required provides a simpler more effective approach. This is now the recommended technique for handling
sets of constants in a program. Let's see how it works.
Constants Defined in a Class
Search WWH ::




Custom Search