Java Reference
In-Depth Information
The answers are yes and no. Yes, this class compiles, but no, it does not defi ne main
properly. A static method can access a static fi eld in the same class, so there is no
problem with the message fi eld. Also, you can write a method called main that does not
have an array of String objects, so the compiler will not complain about the main method
defi ned on line 4. However, this class cannot be executed as a Java application because it
does not successfully declare the proper main method for a Java application.
Let's try it again, this time with the following SayHello class. Does this class compile
and successfully declare the main method?
1. public class SayHello {
2. private static String message = “Hello!”;
3.
4. public static void main(String [] args) {
5. System.out.println(message);
6. }
7. }
The answer is yes to both: SayHello compiles and declares the proper version of main so
that it can be executed as a stand-alone Java application. The following command line runs
the SayHello application:
java SayHello
This command line assumes that you run the command from the directory that contains
the fi le SayHello.class , which in our case is c:\myproject . If you want to run this Java
application from any directory (instead of just c:\myproject ), you need to include
c:\myproject in your CLASSPATH . Figure 1.2 shows SayHello being executed from
c:\myproject , and then being executed from c:\ after the CLASSPATH is correctly set.
Compiling and running the SayHello program from a command prompt
FIGURE 1.2
Search WWH ::




Custom Search