📄 ch29.htm
字号:
<TT>PackageName</TT>. The package line must be the first linein the class's source code (except for blank lines or comments).<H3><A NAME="ExampleCreatingaSimplePackage">Example: Creating a Simple Package</A></H3><P>Suppose that you want to create a class called <TT>DisplayClass</TT>that returns a test string to be displayed in an applet. You wantthis class to be part of a package called DISPLAY. Listing 29.1shows the source code for the <TT>DisplayClass</TT> class:<HR><BLOCKQUOTE><B>Listing 29.1 DisplayClass.java: The </B><I>DisplayClass</I><B>Class.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>package MyPackages.Display;public class DisplayClass{ public String GetDisplayText() { return "Display Text"; }}</PRE></BLOCKQUOTE><HR><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>When you examine Listing 29.1, you may wonder how <TT>DisplayClass</TT> can reference Java's <TT>String</TT> class without including an <TT>import</TT> line at the top of the listing. The class gets away with this because Java automatically imports the java.lang package, where the <TT>String</TT> class is defined.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The first line of Listing 29.1 determines not only the name ofthe package, but also the way it must be stored on your hard drive.That is, the DisplayClass.class file must end up in a folder calledDisplay, which itself must be in a folder called MYPACKAGES. Tocompile DisplayClass.java, follow these steps:<OL><LI>In your CLASSES folder, create a folder called MYPACKAGES.This is where you will create the folders needed by each of thepackages you create.<LI>In the MYPACKAGES folder, create a folder called DISPLAY.This folder will hold any of the classes that are part of the<TT>Display</TT> package.<LI>Type in Listing 29.1 and save it in the DISPLAY folder, underthe name DisplayClass.java. (If you don't want to type, you cancopy the file from this book's CD-ROM.)<LI>Select the MS-DOS Prompt command from the Start menu's Programgroup and switch to the CLASSES\MYPACKAGES\DISPLAY folder, asshown in Figure 29.1.<BR><A HREF="f29-1.gif"><B> Figure 29.1 : </B><I>To compile a package's class, you must switch to the folder in which the class's source code is stored.</I></A><P><LI>At the MS-DOS prompt, type <TT>javac DisplayClass.java</TT>.Java's compiler then compiles the DisplayClass.java file, creatingthe DisplayClass.class file in your DISPLAY folder.</OL><P>As you can see in Figure 29.2, if you now look in your DISPLAYfolder, you'll have not only the original source code file forthe <TT>DisplayClass</TT> class, but also the DisplayClass.classfile, which is the class's byte-code representation that Javacan understand. Congratulations! You've just created your firstpackage.<P><A HREF="f29-2.gif"><B> Figure 29.2 : </B><I>After compiling, you will have the class's .CLASS file on your disk.</I></A><P><H3><A NAME="ExampleUsingtheNewPackage">Example: Using the New Package</A></H3><P>Now that you've created a package, you'd probably like to useit in an applet. To do this, you must first import the class intothe applet's source code file. You can then use the class in exactlythe same way you've been using Java's classes throughout thisbook. Listing 29.2 is an applet, called PackageApplet, that demonstrateshow to use your new package. Listing 29.3 is the applet's HTMLdocument.<HR><BLOCKQUOTE><B>Listing 29.2 PackageApplet.java: An Applet ThatUses Your New Package.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import MyPackages.Display.DisplayClass;public class PackageApplet extends Applet{ public void paint(Graphics g) { Font font = new Font("TimesRoman", Font.PLAIN, 24); g.setFont(font); DisplayClass myClass = new DisplayClass(); String s = myClass.GetDisplayText(); g.drawString(s, 60, 80); }}</PRE></BLOCKQUOTE><HR><HR><BLOCKQUOTE><B>Listing 29.3 PACKAGEAPPLET.htmL: PackageApplet'sHTML Document.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE><title>Applet Test Page</title><h1>Applet Test Page</h1><applet code="PackageApplet.class" width=250 height=250 name="PackageApplet"></applet></PRE></BLOCKQUOTE><HR><P>Notice how the third line in Listing 29.2 imports the <TT>DisplayClass</TT>class from the <TT>Display</TT> package. You also could have usedthe line <TT>import MyPackages.Display.*</TT>, as you did withthe Java packages in the first two lines of the listing. Becausethere is currently only one class in the package, using the asteriskachieves exactly the same results as specifying the class's namein the <TT>import</TT> line. However, when you add other classesto the package, the asterisk will tell Java to include those classes,as well.<P>To see how all this package stuff works with the PackageAppletapplet, follow these steps:<OL><LI>Type in Listings 29.2 and 29.3 and save them in your CLASSESfolder (the same folder that contains your new MYPACKAGES folder).If you prefer, you can copy the listings from this book's CD-ROM.<LI>In your DOS window, switch to the CLASSES directory.<LI>Type <TT>javac PackageApplet.java</TT> to compile the appletinto a .class file.<LI>Run the applet by typing appletviewer packageapplet.html.</OL><P>When you run the PackageApplet applet, you see the window shownin Figure 29.3. The text that's displayed in the applet is acquiredby the call to the <TT>DisplayClass</TT> class's <TT>GetDisplayText()</TT>method. This class is part of your new <TT>Display</TT> class.When you run the applet, Java knows where to find the <TT>Display</TT>class because of the hierarchy of folders you created to mirrorthe MYPACKAGES\DISPLAY \ DisplayClass.class hierarchy.<P><A HREF="f29-3.gif"><B> Figure 29.3 : </B><I>PackageApplet displays the text string obtained from a class defined in your new Display package.</I></A><P><H3><A NAME="ExampleExtendingthePackage">Example: Extending the Package</A></H3><P>Now that you've got the package started, you can extend it simplyby creating new classes that have the line <TT>package MyPackages.Display</TT>at the top of the source code. Thanks to the folder hierarchyyou've developed (and that Java insists upon), all the class files(both source and byte-code) in the <TT>Display</TT> package willend up in the DISPLAY folder. You could have one or a hundred.<P>You can add new packages to your growing library by creating foldersinside the MYPACKAGES folder and storing the new classes there.Suppose, for example, that you want to start a new package called<TT>Shapes</TT>. The classes you want to add to this package arecalled <TT>Star</TT>, <TT>Hexagon</TT>, and <TT>Triangle</TT>.You'd then follow the steps given here:<OL><LI>Create a folder called SHAPES inside the MYPACKAGES folder.This is where you'll store all the files associated with the <TT>Shapes</TT>package.<LI>Create the <TT>Star</TT>, <TT>Hexagon</TT>, and <TT>Triangle</TT>classes in separate source-code files, being sure to place theline <TT>package MyPackages.Shapes;</TT> at the top of each file.<LI>Switch to the C:\CLASSES\MYPACKAGES\SHAPES folder and type<TT>javac Star.java</TT> to compile the <TT>Star</TT> class. Compilethe <TT>Hexagon</TT> and <TT>Triangle</TT> classes in the sameway.<LI>Write the source code for the applet that uses your new <TT>Shapes</TT>package, storing the file in the C:\CLASSES directory. Rememberto put the line <TT>import MyPackages.Shapes.*;</TT> at the topof the file. The asterisk ensures that all classes in the <TT>Shapes</TT>package are imported into the program.</OL><H2><A NAME="Interfaces"><FONT SIZE=5 COLOR=#Ff0000>Interfaces</FONT></A></H2><P>Packages are fairly easy to understand, being little more thana way to organize related classes, whether supplied with Javaor created by a programmer like yourself. Interfaces, on the otherhand, are a concept that is a bit harder to grasp. To really understandJava's interfaces, you have to know about something called multipleinheritance, which is not allowed in Java, but which is oftenused in other object-oriented languages.<P>Multiple inheritance means creating a new class that inheritsbehavior directly from more than one superclass. To make thisconcept a little clearer, look at how you derive classes fromsuperclasses in Java. For example, every applet you've createdso far has been derived from Java's <TT>Applet</TT> class, likethis:<BLOCKQUOTE><PRE>public class AppletName extends Applet</PRE></BLOCKQUOTE><P>The preceding line tells Java that you want to create a new classthat inherits the data fields and methods of the <TT>Applet</TT>class. This is a sample of single inheritance. Now, suppose thatyou had a class of your own, called <TT>MyClass</TT>, that implementedsome capabilities that you also want your new applet to inherit.In a language like C++, you simply add the class to a list ofsuperclasses, like this:<BLOCKQUOTE><PRE>public class AppletName extends Applet, MyClass</PRE></BLOCKQUOTE><P>This would be an example of multiple inheritance if Java allowedsuch a thing. However, for many reasons, Java's designers decidedthat multiple inheritance was too cumbersome and unpredictableto be useful. They still liked the idea, though, of being able
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -