📄 ch29.htm
字号:
to declare a set of behaviors that can be inherited by one ormore classes. So, they came up with interfaces.<H3><A NAME="TheBasicInterface">The Basic Interface</A></H3><P>An interface is very much like a class-with one important difference.None of the methods declared in an interface are implemented inthe interface itself. Instead, these methods must be implementedin any class that uses the interface. In short, interfaces describebehaviors but do not detail how those behaviors will be carriedout.<P>Interfaces are so much like classes, in fact, that they are declaredin almost exactly the same way. You just replace the <TT>class</TT>keyword with the <TT>interface</TT> keyword, like this:<BLOCKQUOTE><PRE>interface MyInterface{}</PRE></BLOCKQUOTE><P>The preceding example is a complete interface, meaning that itcan be compiled, after which other Java programs can referenceit. You compile an interface exactly the same way you compilea class. First, you save the interface's source code in a filewith the .java extension. Then you use the Java compiler, javac,to compile the source code into byte-code form. Just like a normalclass, the byte-code file will have the .class extension.<P>Missing from the preceding sample interface are the methods thatdescribe the interface's behaviors. In the sections that follow,you'll learn how to add this important element to an interface.<H3><A NAME="ExampleCreatinganInterface">Example: Creating an Interface</A></H3><P>Suppose that instead of creating a full-fledged class out of your<TT>Display</TT> package's <TT>DisplayClass</TT> class, you wantto make it an interface. (Yes, just like classes, you can makeinterfaces part of a package.) Listing 29.4 shows how the sourcecode would be modified.<HR><BLOCKQUOTE><B>Listing 29.4 DisplayInterface.java: Creating anInterface.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>package MyPackages.Display;public interface DisplayInterface{ public String GetDisplayText();}</PRE></BLOCKQUOTE><HR><P>The first line in Listing 29.4 is exactly like the first linein Listing 29.1, which shows the original class. The first linespecifies that this interface is to be part of the <TT>MyPackages.Display</TT>package. The second line declares the interface. The only differencehere is the use of the <TT>interface</TT> keyword in place of<TT>class</TT> and the new name, <TT>DisplayInterface</TT>.<P>Now, the real difference between a class and an interface becomesevident. Although Listing 29.4 declares the <TT>GetDisplayText()</TT>method, it doesn't actually implement the method. That is, youcan see from the interface that <TT>GetDisplayText()</TT> is supposedto return a <TT>String</TT> object, but there isn't a clue asto how that <TT>String</TT> object is created or what it contains.Those details are left up to any class that decides to implementthe interface.<P>But before you worry about implementing the interface in a class,you have to compile the interface source code. To do that, followthese steps:<OL><LI>Type in Listing 29.3 and save it in the DISPLAY folder, underthe name DisplayInterface.java. (If you don't want to type, youcan copy 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.<LI>At the MS-DOS prompt, type <TT>javac DisplayInterface.java</TT>.Java's compiler then compiles the DisplayInterface.java file,creating the DisplayInterface.class file in your DISPLAY folder.</OL><H3><A NAME="ImplementinganInterface">Implementing an Interface</A></H3><P>Now that you have your new interface compiled, you can implementit in a class. This means not only telling Java that you'll beusing the interface, but also implementing the interface withinthe new class. That is, every method that is listed in the interface'sdeclaration must be defined in the class's source code. Listing29.5 is a new applet, called InterfaceApplet, that shows how toimplement the <TT>DisplayInterface</TT> interface. When you compileand run this applet, you see exactly the same display as thatproduced by the original version, PackageApplet. Notice how thelisting uses the <TT>implements</TT> keyword to tell Java thatthe applet will be implementing the <TT>DisplayInterface</TT>interface.<HR><BLOCKQUOTE><B>Listing 29.5 InterfaceApplet.java: An Applet ThatImplements the </B><I>DisplayInterface</I><B> Interface.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import MyPackages.Display.DisplayInterface;public class InterfaceApplet extends Applet implements DisplayInterface{ public void paint(Graphics g) { Font font = new Font("TimesRoman", Font.PLAIN, 24); g.setFont(font); String s = GetDisplayText(); g.drawString(s, 60, 80); } public String GetDisplayText() { return "Display Text"; }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the applet uses the classes in the <TT>awt</TT>package.<BR>Tell Java that the applet uses the classes in the <TT>applet</TT>package.<BR>Tell Java that the applet uses the <TT>Display</TT> package's<TT>DisplayInterface</TT>.<BR>Derive <TT>InterfaceApplet</TT> from <TT>Applet</TT> and implement<TT>DisplayInterface</TT>.<BR> Override the <TT>paint()</TT> method.<BR> Create and set the <TT>Graphics</TT> object's font.<BR> Get the display string.<BR> Draw the display string.<BR> Define the interface's <TT>GetDisplayText()</TT> method.<BR> Return the display string.<BR></BLOCKQUOTE><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>TIP</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>A class can implement as many interfaces as it needs to. To implement multiple interfaces, just list the interfaces after the <TT>implements</TT> keyword, separating each interface name from the others with a comma. Remember, however, that you must implement in your new class all the methods declared in all the interfaces you implement.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>There's quite a lot to learn about interfaces. However, due to the skill level of this book and the fact that you probably won't have to worry about interfaces until you're an experienced Java programmer, only the basics have been presented here. Chances are good that you won't have to create interfaces at all. It's just good to know they're there in case you need them.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Packages are a great way to create and organize class libraries.The more Java code you write, the more you'll appreciate the abilityto create your own packages. Although you won't need to use interfacesfor some time to come (if at all), interfaces are a unique elementof the Java programming language. Although other object-orientedlanguages such as C++ allow multiple inheritance, only Java supportsthe idea of interfaces, which can be powerful tools when they'reneeded.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What's a package?<LI>How do you tell Java that a source-code file uses a particularpackage?<LI>How do you add a class or interface to a package?<LI>How do you tell Java that the class you're creating implementsa particular interface?<LI>What's the biggest difference between an interface and a class?<LI>How are interfaces similar to classes?<LI>How does the complete name of a package relate to the package'sstorage on your disk?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Add a new class to the Display package. This class shouldreturn an integer representing the size of the font to use whendrawing the display text.<LI>Change the class you wrote in exercise 1 to an interface.Write an applet that implements the new interface.</OL><HR><HR WIDTH="100%"></P></CENTER><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>, All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -