Java Reference
In-Depth Information
Static member imports and overloaded methods
A static import declaration imports a name , not any one specific member with that
name. Because Java allows method overloading and allows a type to have fields and
methods with the same name, a single static member import declaration may
actually import more than one member. Consider this code:
a x
import static java . util . Arrays . sort ;
This declaration imports the name “sort” into the namespace, not any one of the 19
sort() methods defined by java.util.Arrays . If you use the imported name sort
to invoke a method, the compiler will look at the types of the method arguments to
determine which method you mean.
It is even legal to import static methods with the same name from two or more dif‐
ferent types as long as the methods all have different signatures. Here is one natural
example:
import static java . util . Arrays . sort ;
import static java . util . Collections . sort ;
You might expect that this code would cause a syntax error. In fact, it does not
because the sort() methods defined by the Collections class have different signa‐
tures than all of the sort() methods defined by the Arrays class. When you use the
name “sort” in your code, the compiler looks at the types of the arguments to deter‐
mine which of the 21 possible imported methods you mean.
Java File Structure
This chapter has taken us from the smallest to the largest elements of Java syntax,
from individual characters and tokens to operators, expressions, statements, and
methods, and on up to classes and packages. From a practical standpoint, the unit
of Java program structure you will be dealing with most often is the Java file. A Java
file is the smallest unit of Java code that can be compiled by the Java compiler. A
Java file consists of:
• An optional package directive
• Zero or more import or import static directives
• One or more type definitions
These elements can be interspersed with comments, of course, but they must appear
in this order. This is all there is to a Java file. All Java statements (except the package
and import directives, which are not true statements) must appear within methods,
and all methods must appear within a type definition.
Java files have a couple of other important restrictions. First, each file can contain at
most one top-level class that is declared public . A public class is one that is
designed for use by other classes in other packages. A class can contain any number
Search WWH ::




Custom Search