Thursday, July 25, 2013

Importing the Math Class Methods

It would be a lot more convenient if you were able to avoid having to qualify the name of every method in the Math class that you use with the class name. The code would be a lot less cluttered if you could write floor(radius) instead of Math.floor(radius) for example. Well, you can. All you need to do is put the following statement at the beginning of the source file:

import static java.lang.Math.*; // Import static class members

This statement makes the names of all the static members of the Math class available for use in your Java program code without having to qualify them with the class name. This includes constants such as PI as well as static methods. You can try this statement in the PondRadius example. With this statement at the beginning of the source file, you will be able to remove the qualification by the class name Math from all the members of this class that the program uses.

In the statement indicates that all static names are to be imported. If you wanted to import just the names from the Math class that the PondRadius program uses, you would write:

import static java.lang.Math.floor; // Import floor
import static java.lang.Math.sqrt; // Import sqrt
import static java.lang.Math.round; // Import round
import static java.lang.Math.PI; // Import PI

These statements import individually the four names from the Math class that the program references. You could use these four statements at the beginning of the program in place of the previous import statement that imports all the static names.

No comments:

Post a Comment

Thanks for Commenting......