«^»
4.3. Deriving from Applet instead of declaring a main method

So far the Java source code that we have produced has been for programs that we have run on our own computer. Such programs are called Java applications. We are now about to produce Java source code that is to be run by the Java interpreter of a WWW browser. This kind of source code is called a Java applet.

The source code for an application is different from that for an applet. For an application, we provide a class that has a method called main, and this is the method that is executed first when we run the java command, the command that executes the Java interpreter. For an applet, we do not provide a main method: instead, we use inheritance to derive a class from java.applet.Applet and override methods like paint, init, start, stop and destroy. We do this because this is what the Java interpreter contained in the WWW browser expects.

Here is an example of some Java source code that is a Java applet:

0275: // The code of the HelloApplet applet paints a string.   // HelloApplet.java
0276: // Barry Cornelius, 24th April 1999
0277: import java.applet.Applet;
0278: import java.awt.Graphics;
0279: public class HelloApplet extends Applet
0280: {
0281:    public void paint(Graphics pGraphics)
0282:    {
0283:       pGraphics.drawString("Hello world", 50, 25);
0284:    }
0285: }

This can be compiled in the usual way:

javac HelloApplet.java
in order to produce the file HelloApplet.class.

Suppose we tell a WWW browser to read the WWW page that is in the file HelloApplet.html. When it reaches the APPLET tag, it knows it has to obtain the bytecodes contained in the file HelloApplet.class. When these bytecodes have arrived, the Java interpreter contained in the WWW browser will create an object of the HelloApplet class. And, because we have overridden the paint method, the code of this method will be executed. The result is displayed within the window of the browser (as shown in the Figure). Here is a link to a WWW page containing these HTML instructions: http://www.dur.ac.uk/barry.cornelius/papers/advanced+/code2/Applets/simple/HelloApplet.html.

The code of HelloApplet is simple, and so the only classes that it depends on are classes from Java's Core APIs. However, normally the code for an applet will be dependent on other classes that the author has written. If this is the case, then, as the Java interpreter executes the bytecodes, it will detect that the bytecodes of other classes that need to be downloaded, and so it will return to the author's WWW site to download the bytecodes from the appropriate .class files.