Java Reference
In-Depth Information
You could define a class to hold the same set of constants that you saw defined in an interface in the previous
section, like this:
package conversions;
// Package for conversions
public class ConversionFactors {
public static final double INCH_TO_MM = 25.4;
public static final double OUNCE_TO_GRAM = 28.349523125;
public static final double POUND_TO_GRAM = 453.5924;
public static final double HP_TO_WATT = 745.7;
public static final double WATT_TO_HP = 1.0/HP_TO_WATT;
}
Directory "TryConversions/conversions"
Of course, you can access the members of the ConversionsFactors class from outside by using the
qualified names of the data members — ConversionFactors.HP_TO_WATT , for example. An alternative and
possibly more convenient approach is to import the static members of the class into any class that needs
to use any of the constants. This allows the constants to be referred to by their unqualified names. In this
case, the class must be in a named package, because the import statement cannot be applied to the unnamed
package.
Here's how you might use it:
import static conversions.ConversionFactors.*; // Import static members
public class MyOtherClass {
// This class can access any of the constants defined in ConversionFactors
public static double poundsToGrams(double pounds) {
return pounds*POUND_TO_GRAM;
}
// Plus the rest of the class definition...
}
Now you can access any of the static members of the ConversionFactors class using their unqualified
names from any source file. All that is necessary is the import statement for the static members of the class.
Alternatively, you could just import the static members you want to use. For example, you could use the
following import statement if you just want to use the constant with the name POUND_TO_GRAM :
import static conversions.ConversionFactors.POUND_TO_GRAM;
Let's see it working in an example.
Search WWH ::




Custom Search