10.7 Class Name Abbreviations

The Java language permits you to abbreviate class names by omitting the package name if the class has been imported. JVM instructions always require the fully qualified form of the class name. If a Java program uses an abbreviated class name, then the compiler has to find the class name in the list of imported classes.

Imported classes are listed at the beginning of the Java program, right after the package statement. Suppose the program being compiled starts like this:

 package your.package; import my.package.Person; import java.util.Hashtable; import java.io.*; 

The * means that every class with that package name is imported. It's up to the compiler to find the definitions for those classes. The way the definitions are found varies from compiler to compiler. For many Java compilers, an environment variable called CLASSPATH is used. The CLASSPATH environment variable contains a list of directories. The Java compiler scans those directories looking for files ending in .class. These are treated as class files. If the package name of the class matches the import directive, then the class is imported.

Importing a class doesn't add any code to your program. The only effect is to allow you to abbreviate names in Java code.

Every program has two implicit import statements:

 import java.lang.*; import thisPackage.*; 

where thisPackage is the package name specified on the package statement; in this case, it is your.package. This Java expression creates a new instance of the class Hashtable:

 new Hashtable() 

The compiler looks for every imported class named Hashtable. One such class is java.util.Hashtable, which was imported explicitly. The compiler checks all the other imported classes, looking for others named Hashtable. It checks for a your.package.Hashtable, a java.io.Hashtable, and a java.lang.Hashtable.

Table 10.6. Selecting an arithmetic operator
Operator Type
  int long float double
+ iadd ladd fadd dadd
- isub lsub fsub dsub
/ idiv ldiv fdiv ddiv
* imul lmul fmul dmul
% irem lrem frem drem
unary - ineg lneg fneg dneg
& iadd land - -
| ior lor - -
^ ixor lxor - -

If none is found or if more than one is found, then the compiler doesn't know which class the programmer is referring to by the name Hashtable, and it should be treated as an error. If exactly one is found, then the compiler uses that as the full name of the class.

The code generated for this new expression is

 new java/util/Hashtable dup invokespecial java/util/Hashtable/<init>()V 

Note the shift from periods (.) to slashes (/) in the package separator. JVM programs always use slashes and Java programs always use periods.



Programming for the Java Virtual Machine
Programming for the Javaв„ў Virtual Machine
ISBN: 0201309726
EAN: 2147483647
Year: 1998
Pages: 158
Authors: Joshua Engel

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net