Java Reference
In-Depth Information
TRY IT OUT: Importing Constants into a Program
Save the ConversionFactors class definition ConversionFactors.java in a directory with the name
conversions . Here's a simple class that uses the constants defined in the utility class ConversionFact-
ors :
import static conversions.ConversionFactors.*;
// Import static
members
public class TryConversions {
public static double poundsToGrams(double pounds) {
return pounds*POUND_TO_GRAM;
}
public static double inchesToMillimeters(double inches) {
return inches*INCH_TO_MM;
}
public static void main(String args[]) {
int myWeightInPounds = 180;
int myHeightInInches = 75;
System.out.println("My weight in pounds: " +myWeightInPounds +
" \t-in grams: "+
(int)poundsToGrams(myWeightInPounds));
System.out.println("My height in inches: " +myHeightInInches +
" \t-in millimeters: "+
(int)inchesToMillimeters(myHeightInInches));
}
}
Directory "TryConversions"
Save the TryConversions.java file in the TryConversions directory. Don't forget that you must in-
clude the path to your conversions package when you compile this program. If the conversions direct-
ory is a subdirectory of C:\MyPackages , the command to compile the program with TryConversions as
the current directory is:
javac -classpath "C:\MyPackages" TryConversions.java
When you compile and execute this example, you should see the following output:
My weight in pounds: 180 -in grams: 81646
My height in inches: 75 -in millimeters: 1905
How It Works
Search WWH ::




Custom Search