Java Reference
In-Depth Information
of nested or inner classes that are public . We'll see more about the public modifier
and nested classes in Chapter 3 .
The second restriction concerns the filename of a Java file. If a Java file contains a
public class, the name of the file must be the same as the name of the class, with the
extension .java appended. Therefore, if Point is defined as a public class, its source
code must appear in a file named . Regardless of whether your classes are
public or not, it is good programming practice to define only one per file and to
give the file the same name as the class.
When a Java file is compiled, each of the classes it defines is compiled into a separate
class file that contains Java byte codes to be interpreted by the Java Virtual Machine.
A class file has the same name as the class it defines, with the extension .class
appended. Thus, if the file defines a class named Point , a Java compiler
compiles it to a file named Point.class . On most systems, class files are stored in
directories that correspond to their package names. The class com.davidflana
gan.examples.Point is thus defined by the class file com/davidlanagan/examples/
Point.class .
The Java interpreter knows where the class files for the standard system classes are
located and can load them as needed. When the interpreter runs a program that
wants to use a class named com.davidflanagan.examples.Point , it knows that the
code for that class is located in a directory named com/davidlanagan/examples/
and, by default, it “looks” in the current directory for a subdirectory of that name.
In order to tell the interpreter to look in locations other than the current directory,
you must use the -classpath option when invoking the interpreter or set the CLASS
PATH environment variable. For details, see the documentation for the Java inter‐
preter, java , in Chapter 8 .
Deining and Running Java Programs
A Java program consists of a set of interacting class definitions. But not every Java
class or Java file defines a program. To create a program, you must define a class that
has a special method with the following signature:
public static void main ( String [] args )
This main() method is the main entry point for your program. It is where the Java
interpreter starts running. This method is passed an array of strings and returns no
value. When main() returns, the Java interpreter exits (unless main() has created
separate threads, in which case the interpreter waits for all those threads to exit).
To run a Java program, you run the Java interpreter, java , specifying the fully quali‐
fied name of the class that contains the main() method. Note that you specify the
name of the class, not the name of the class file that contains the class. Any addi‐
tional arguments you specify on the command line are passed to the main() method
as its String[] parameter. You may also need to specify the -classpath option (or
Search WWH ::

Custom Search