Java Reference
In-Depth Information
Although this is rather verbose and certainly doesn't help the readability of the program, it does ensure
you have no conflict between this class and any other
Sphere
class that might be part of your program. You
can usually contrive that your class names do not conflict with those in the commonly used standard Java
packages, but in cases where you can't manage this, you can always fall back on using fully qualified class
names. Indeed, on some occasions, you have to do this. This is necessary when you are using two different
classes from different packages that share the same basic class name.
Importing Static Class Members
As you have seen in some of the examples, you can import the names of static members of a class from a
named package into your program. This enables you to reference such static members by their simple un-
qualified names. In the
Sphere
class that you developed earlier in this chapter, you could have used the
constant
PI
that is defined in the
Math
class by using its fully qualified name,
Math.PI
, in the definition of
the volume method:
double volume() {
return 4.0/3.0*Math.PI*radius*radius*radius;
}
This obviates the need for the static member of the
Sphere
class with the name
PI
and would provide a
much more accurate definition of the value of π.
However, the
Math
prefix to the name
PI
doesn't really add to the clarity of the code, and it would be
better without it. You can remove the need for prefixing
PI
with the
Math
class name by importing the
PI
member name from the
Math
class:
import static java.lang.Math.PI;
class Sphere {
// Class details as before...
double volume() {
return 4.0/3.0*PI*radius*radius*radius;
}
}
It is clear what
PI
means here and the code is not cluttered up with the class name prefix.
You can also import all the static members of a class using
*
notation. For example:
import static java.lang.Math.*; // Import all static members of the Math class
With this statement at the beginning of a source file, you can refer to any of the static members of the
Math
class without qualifying them with the class name. Thus you can use methods such as
sqrt()
,
abs()
,
random()
, and so on, without the need for the
Math
prefix to the method names. Of course, using the
*
notation to import all the static names in a class does increase the risk of clashes between the names you are
importing and the names you define in your code.
Note that the
import
statement, and that includes its use for importing static members of a class, applies
only to classes that are defined in a named package. This is particularly relevant in the context of static im-
port. If you want to import the names of a static member of a class that you define then you
must
put the
definition of a class in a named package. You cannot import the names of static members of a class that is