|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The first two lines of the following listing import two classes used in the applet:AppletandGraphics.import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }If you removed the first two lines, the applet could still compile and run, but only if you changed the rest of the code like this:
As you can see, importing thepublic class HelloWorld extends java.applet.Applet { public void paint(java.awt.Graphics g) { g.drawString("Hello world!", 50, 25); } }AppletandGraphicsclasses lets the program refer to them later without any prefixes. Thejava.applet.andjava.awt.prefixes tell the compiler which packages it should search for theAppletandGraphicsclasses. Both thejava.appletandjava.awtpackages are part of the core Java API -- API that every Java program can count on being in the Java environment. Thejava.appletpackage contains classes that are essential to Java applets. Thejava.awtpackage contains the most frequently used classes in the Abstract Window Toolkit (AWT), which provides the Java graphical user interface (GUI).You might have noticed that the A Closer Look at HelloWorld
example from the previous lesson uses the
Systemclass without any prefix, and yet does not import theSystemclass. The reason is that theSystemclass is part of thejava.langpackage, and everything in thejava.langpackage is automatically imported into every Java program.Besides importing individual classes, you can also import entire packages. Here's an example:
In the Java language, every class is in a package. If the source code for a class doesn't have a package statement at the top, declaring the package the class is in, then the class is in the default package. Almost all of the example classes in this tutorial are in the default package. See Creating and Using Packagesimport java.applet.*; import java.awt.*; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }for information on using the
packagestatement.Within a package, all classes can refer to each other without prefixes. For example, the
java.awt Componentclass refers to thejava.awt Graphicsclass without any prefixes, without importing theGraphicsclass.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.