📄 ch14.htm
字号:
programmers at Sun created the <TT>Applet</TT> class, they didn'tthink to add the methods needed to play Tic-Tac-Toe. You'll haveto add those methods yourself.<H3><A NAME="ExampleAddingFieldsandMethods">Example: Adding Fields and Methods</A></H3><P>Take the <TT>MyClass</TT> class that you created earlier in thischapter (shown in Listing 14.3). Suppose you want to create anew class that has a new data field called <TT>myNewField</TT>,as well as a constructor and methods for setting and retrievingthe value of this new data field. You might come up with somethinglike Listing 14.6.<HR><BLOCKQUOTE><B>Listing 14.6 MYSUBCLASS.JAVA: Creating a Subclass.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import MyClass;class MySubClass extends MyClass{ private int myNewField; public MySubClass(int value) { super(value); myNewField = value; } public void SetNewField(int value) { myNewField = value; } public int GetNewField() { return myNewField; }}</PRE></BLOCKQUOTE><HR><P>The file containing the <TT>MySubClass</TT> class first importsthe <TT>MyClass</TT> file, because Java will need the informationcontained in that file. In the constructor, the class first calls<BLOCKQUOTE><PRE>super(value);</PRE></BLOCKQUOTE><P>which ensures that the superclass (<TT>MyClass</TT>) is properlyinitialized by calling its constructor. The keyword <TT>super</TT>refers to the class's superclass. After calling the superclass'sconstructor, the <TT>MySubClass</TT> constructor initializes thenew data field, <TT>myNewField</TT>. The new class also suppliesnew methods for setting and getting the value of <TT>myNewField</TT>.In short, <TT>MySubClass</TT> now has two data fields-<TT>myField</TT>,which it inherited from <TT>MyClass</TT>, and the new <TT>myNewField</TT>-andfour methods-<TT>SetField()</TT> and <TT>GetField</TT>, whichit inherited from <TT>MyClass</TT>, and the new <TT>SetNewField()</TT>and <TT>GetNewField()</TT> methods.<H2><A NAME="ExampleUsingaSubclassinaProgram"><FONT SIZE=5 COLOR=#Ff0000>Example: Using a Subclass in a Program</FONT></A></H2><P>Now that you have the <TT>MySubClass</TT> subclass, it might benice to see how it works in a real programming situation. Applet20,which is shown in Listing 14.7, does the honors of putting <TT>MySubClass</TT>to work. In most places, compared to Applet19, the applet merelyreplaces occurrences of <TT>MyClass</TT> with <TT>MySubClass</TT>.The <TT>paint()</TT> method has to work a bit harder, though,calling all four of <TT>MySubClass</TT>'s methods to prove theywork.<HR><BLOCKQUOTE>Listing 14.7 APPLET20.JAVA: Using a Subclass in a Program.<BR></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import MySubClass;public class Applet20 extends Applet{ MySubClass mySubObject; TextField textField1; TextField textField2; public void init() { mySubObject = new MySubClass(1); textField1 = new TextField(10); add(textField1); textField1.setText("1"); textField2 = new TextField(10); add(textField2); textField2.setText("2"); } public void paint(Graphics g) { String s = textField1.getText(); int value = Integer.parseInt(s); mySubObject.SetField(value); value = mySubObject.GetField(); s = String.valueOf(value); g.drawString("The myField data field", 30, 80); g.drawString("is now set to this value:", 40, 95); g.drawString(s, 90, 125); s = textField2.getText(); value = Integer.parseInt(s); mySubObject.SetNewField(value); value = mySubObject.GetNewField(); s = String.valueOf(value); g.drawString("The myNewField data field", 30, 155); g.drawString("is now set to this value:", 40, 170); g.drawString(s, 90, 200); } public boolean action(Event event, Object arg) { repaint(); return true; }}</PRE></BLOCKQUOTE><HR><P>When you run Applet20 under Appletviewer, you see the window shownin Figure 14.4. Use the first text box to enter values for theoriginal <TT>myField</TT> data field. Use the second text boxto enter values for <TT>myNewField</TT>. Whenever you press Enter,the applet reads the values from the boxes and calls <TT>MySubClass</TT>'smethods to set the new values and to retrieve the set values fromthe object.<P><A HREF="f14-4.gif"><B> Figure 14.4 : </B><I>This is Appletviewer running the Applet20 applet.</I></A><P><H2><A NAME="OverridingMethodsoftheSuperclass"><FONT SIZE=5 COLOR=#Ff0000>Overriding Methods of the Superclass</FONT></A></H2><P>If you've been reading the pseudocode sections that follow manyof the listings in this book, you've seen the term "overriding"many times. When you override a method, you are creating a newversion of a method that's part of the superclass. For example,in many of the applets you've created, you've overridden methodslike <TT>init()</TT>, <TT>paint()</TT>, and <TT>action()</TT>.All of these methods are defined in some general way in the <TT>Applet</TT>superclass. When you derive a new class from applet, you can overridethese methods to perform the tasks you want them to perform, ratherthan the general tasks assigned to them by the <TT>Applet</TT>class.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>In general object-oriented programming discussions, the term "derive" means exactly the same thing as "subclass" (when the latter is used as a verb). Ditto for the terms "base class" and "superclass," which are the same thing. In other words, when you derive a new class from a base class, you are subclassing a new class from a superclass.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>For example, you know that, when Java starts up an applet, itcalls the applet's <TT>init()</TT> method. Here's how the <TT>Applet</TT>class defines <TT>init()</TT>:<BLOCKQUOTE><PRE>public void init(){}</PRE></BLOCKQUOTE><P>No, your eyes aren't fooling you. In the <TT>Applet</TT> class,the <TT>init()</TT> method does nothing at all. It's only thereso you can override it in your own class. Here's how it all works:When you derive your applet class from <TT>Applet</TT>, your appletclass inherits all of <TT>Applet</TT>'s data fields and methods.If you don't override a method, Java calls the original versionas necessary. In other words, if you don't override <TT>init()</TT>in your applet class, when Java starts your applet, it calls the<TT>Applet</TT> class's version of <TT>init()</TT>, which doesnothing. However, if you override <TT>init()</TT> in your class,Java is smart enough to call the new version rather than the originaldo-nothing version. Cool, eh?<H2><A NAME="TheIthisIKeyword"><FONT SIZE=5 COLOR=#Ff0000>The <I>this</I> Keyword</FONT></A></H2><P>There may be times when you need to explicitly refer to an objectfrom within the object's methods. For example, you might needto pass a reference to the object as an argument in a method call.When you need to refer to the object explicitly, use the <TT>this</TT>keyword. In many cases, the <TT>this</TT> keyword is implicitin the method call or variable reference. For example, insidean object that has the data field <TT>dataField</TT>, the line<BLOCKQUOTE><PRE>dataField = 1;</PRE></BLOCKQUOTE><P>is the same as<BLOCKQUOTE><PRE>this.dataField = 1;</PRE></BLOCKQUOTE><P>In the first case, the <TT>this</TT> keyword is implicit, whereasin the second case, you've included it explicitly. If you neededto pass a reference to the object as an argument, you might writesomething like this:<BLOCKQUOTE><PRE>SomeMethod(this);</PRE></BLOCKQUOTE><P>Of course, the <TT>SomeMethod()</TT> method would have been writtento accept an object of <TT>this</TT>'s type as its single argument.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>If you've never done any object-oriented programming, it mighttake you a while to get used to using classes. Classes are thesingle biggest hurdle to jump when making the transition fromnormal procedural programming to object-oriented programming (OOP).Just think of classes as a way to provide another level of abstractionto your programs. In your non-OOP programs, you had program elementscalled programs, files, and procedures, listed in the order oftheir level of abstraction. Now, you can add classes to the endof the list, right between files and procedures.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What is a class?<LI>How do classes help you to organize your programs?<LI>What are the three parts of a simple, empty class?<LI>What two elements do you add to complete the class?<LI>How do you create an object from a class?<LI>How do you use a class that's defined in a different filethan the file that accesses the class?<LI>What is inheritance and how does it help you create new classesquickly?<LI>What is a subclass and a superclass?<LI>How do you create a subclass?<LI>How do you override a method inherited from a superclass?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write a basic, empty class called <TT>TestClass</TT>.<LI>Add to <TT>TestClass</TT> a string data field called <TT>data1</TT>.This data field should be private to the class.<LI>Add to <TT>TestClass</TT> a constructor that accepts a startingvalue for <TT>data1</TT> as its single argument, and public methodsfor setting and retrieving the value of <TT>data1</TT>. Call thesemethods <TT>SetData()</TT> and <TT>GetData()</TT>.<LI>Compile the finished class.<LI>Write a subclass called <TT>TestSubClass</TT> that is derivedfrom <TT>TestClass</TT> and that adds an integer data field called<TT>data2</TT> (declared as <TT>private</TT>) and a public methodcalled <TT>CreateDataString()</TT> that creates a string objectfrom <TT>data1</TT> and <TT>data2</TT>. That is, if <TT>data1</TT>is equal to <TT>Java is cool!</TT> and <TT>data2</TT> is equalto 15, the <TT>CreateDataString()</TT> method should return <TT>Javais cool! 15</TT> as a single string object. Also, create publicmethods called <TT>SetData2()</TT> and <TT>GetData2()</TT> forsetting and retrieving the value of <TT>data2</TT>, as well asa constructor that accepts arguments for the starting values of<TT>data1</TT> and <TT>data2</TT>.<LI>Modify Applet20 so that it creates an object of the <TT>TestSubClass</TT>class. You should provide text boxes for enabling the user toset <TT>data1</TT> and <TT>data2</TT>, as well as write <TT>paint()</TT>so that it displays the string returned by <TT>CreateDataString()</TT>.Figure 14.5 shows what the ClassApplet applet should look like.(You can find the solutions for these exercises in the CHAP14folder of this book's CD-ROM.) <BR><A HREF="f14-5.gif"><B> Figure 14.5 : </B><I>This is ClassApplet running under Appletviewer.</I></A><P></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 + -