Java Reference
In-Depth Information
Notice that the bytecode file Vehicle.class is not in the c:\src folder. To find
the bytecode, look in your c:\my_bytecode folder. You should see a com direc-
tory, and in com a wiley directory, and in wiley a trans directory.
By the way, we are not done with this example. Vehicle.class is where it
needs to be, but how does the compiler or JVM find it, especially because we
put it in an arbitrary folder named c:\my_bytecode? The compiler and JVM
need to know about c:\my_bytecode, and they find it by checking the CLASS-
PATH environment variable, discussed next.
Suppose that we write a class called CarDealer that uses our Vehicle class in
the com.wiley.trans package. No matter what package we put CarDealer in,
the compiler is going to have to find Vehicle.class before CarDealer compiles.
The compiler knows that Vehicle is in the com.wiley.trans package, because
we are going to import that package. The compiler therefore knows to look for
a directory structure \com\wiley\trans; however, and this is an important
point in Java that tends to cause much frustration, the compiler does not know
to look in the c:\my_bytecode folder. That directory was arbitrarily named,
and in fact, \com\wiley\trans could easily be somewhere else on our hard
drive or out on a network file system somewhere.
The Java compiler and JVM look for bytecode located in directories found in
the CLASSPATH environment variable. With the CLASSPATH environment
variable, the bytecode can be in arbitrary directories. In our Vehicle example,
because we put the bytecode in the c:\my_bytecode directory, we need to add
this directory to our CLASSPATH.
Why have we not had to use CLASSPATH until now? Because in all of the
examples and labs up until now, all of the bytecode needed has been in
the same folder, and if no CLASSPATH environment variable is found, the
compiler and JVM look in the current directory.
The best way to see how CLASSPATH works is hands on, so let's finish our
example with the Vehicle class that we started earlier. Continue with the fol-
lowing steps.
Step 3: Write the CarDealer Class
The following CarDealer class is a program that uses the Vehicle class.
CarDealer is in a different package, so the import statement is used to import
the Vehicle class. Type in the CarDealer class, and save it in the c:\src directory
with Vehicle.java.
package com.wiley.programs;
import com.wiley.trans.Vehicle;
public class CarDealer
Search WWH ::




Custom Search