📄 ch14.htm
字号:
be defined as <TT>public</TT>, methods that must be callable onlyfrom the class and its derived classes should be defined as <TT>protected</TT>,and methods that must be callable only from within the class shouldbe declared as <TT>private</TT>.<P>Suppose <TT>myField</TT> is defined as <TT>private</TT>, and younow want to be able to set the value of <TT>myField</TT> fromoutside the <TT>MyClass</TT> class. Because that data field isdefined as <TT>private</TT>, meaning it can be accessed only fromwithin the same class, you cannot access it directly by name.To solve this problem, you can create a public method that canset the value for you. You might also want to create a methodthat returns the value of the field, as well, as shown in Listing14.3.<HR><BLOCKQUOTE><B>Listing 14.3 LST14_3.TXT: Adding a Method to theClass.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>class MyClass{ private int myField; public MyClass(int value) { myField = value; } public void SetField(int value) { myField = value; } public int GetField() { return myField; }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Start defining the <TT>MyClass</TT> class.<BR> Declare the class's <TT>myField</TT> data field.<BR> Define the class's constructor.<BR> Initialize the data field.<BR> Start defining the <TT>SetField()</TT> method.<BR> Set the data field to the value passed to <TT>SetField().<BR></TT> Start Defining the <TT>GetField()</TT> method.<BR> Return the value of the <TT>myField</TT> data field.<BR></BLOCKQUOTE><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>According to the rules of strict object-oriented design, all class data fields should be declared as <TT>private</TT>. Some programmers would go so far as to say that you should not even provide access to data fields through public methods. However, you'll see these rules broken a lot, even by programmers hired by big companies like Microsoft, Borland, and Sun. As you become more familiar with object-oriented programming, you'll better understand why the rules were made and when it's appropriate to break them.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="ExampleUsingClassesinApplets"><FONT SIZE=5 COLOR=#Ff0000>Example: Using Classes in Applets</FONT></A></H2><P>Up till now, you've been writing applets using the classes alreadysupplied as part of Java. Now, you'll see how to use your ownclasses in applets. This will help you understand not only howyour own classes work, but also help you to understand why youused Java's classes as you did. Follow the steps below to seehow all this class stuff works.<OL><LI>Type Listing 14.3 and save it to your CLASSES folder underthe name <TT>MyClass.java</TT>. (If you don't want to type, youcan find the listing on this book's CD-ROM, in the CHAP14 folder.)<LI>Start a DOS session by selecting Programs/MS-DOS Prompt fromthe Start menu. The DOS window appears, as shown in Figure 14.1.<BR><A HREF="f14-1.gif"><B> Figure 14.1 : </B><I>This is the DOS prompt window.</I></A><P><LI>Type <TT>CD C:\CLASSES</TT> to switch to your CLASSES folder.<LI>Type <TT>javac MyClass.java</TT> to compile the <TT>MyClass</TT>class. You'll then find the <TT>MyClass.class</TT> file in yourCLASSES folder.<LI>Type Listing 14.4 and save it as <TT>Applet19.java</TT> inyour CLASSES folder.<HR><BLOCKQUOTE><B>Listing 14.4 Applet19.java: An Applet That Usesthe </B><I>MyClass</I><B> Class</B>.<BR></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import MyClass;public class Applet19 extends Applet{ MyClass myObject; TextField textField1; public void init() { myObject = new MyClass(1); textField1 = new TextField(10); add(textField1); textField1.setText("1"); } public void paint(Graphics g) { String s = textField1.getText(); int value = Integer.parseInt(s); myObject.SetField(value); value = myObject.GetField(); s = String.valueOf(value); g.drawString("The data field of the object", 30, 80); g.drawString("is now set to this value:", 40, 95); g.drawString(s, 90, 125); } public boolean action(Event event, Object arg) { repaint(); return true; }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the program uses the <TT>awt </TT>package.<BR>Tell Java that the program uses the <TT>applet</TT> package.<BR>Tell Java that the program uses the <TT>MyClass</TT> class.<BR>Derive the <TT>Applet19</TT> class from the <TT>Applet</TT> class.<BR> Declare an object of the <TT>MyClass</TT> class.<BR> Declare a <TT>TextField</TT> object.<BR> Override the <TT>Applet</TT> class's <TT>init()</TT> method.<BR> Create an object of the <TT>MyClass</TT> class.<BR> Create a <TT>TextField</TT> object.<BR> Add the <TT>TextField</TT> object to the applet.<BR> Set the <TT>TextField</TT> object's text.<BR> Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR> Get the text from the <TT>TextField</TT> object.<BR> Convert the text to an integer.<BR> Set <TT>myObject</TT>'s <TT>myField</TT> data field.<BR> Get the value of <TT>myField</TT> from <TT>myObject.<BR></TT> Convert the value to a string.<BR> Draw the applet's display area.<BR> Override the <TT>Applet</TT> class's <TT>action()</TT> method.<BR> Repaint the applet's display area.<BR> Tell Java the method executed okay.</BLOCKQUOTE><LI>Type <TT>javac Applet19.java</TT> to compile the Applet19applet. You'll then have the <TT>Applet19.class</TT> file in yourCLASSES folder.<LI>Type Listing 14.5 and save the file as APPLET19.htmL.</OL><HR><BLOCKQUOTE><B>Listing 14.5 APPLET19.htmL: The HTML Document forApplet19.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE><title>Applet Test Page</title><h1>Applet Test Page</h1><applet code="Applet19.class" width=200 height=200 name="Applet19"></applet></PRE></BLOCKQUOTE><HR><P>You're now ready to run the Applet19 applet, which uses the <TT>MyClass</TT>class. To run the program, type <TT>APPLETVIEWER APPLET19.htmL</TT>.When you do, you see the window shown in Figure 14.2.<P><A HREF="f14-2.gif"><B> Figure 14.2 : </B><I>This is Applet19 running under Appletviewer.</I></A><P><P>The applet's display area shows the current setting of <TT>MyClass</TT>'sdata field, <TT>myField</TT>. You can change this setting by typinga new value into the text box and pressing Enter.<H2><A NAME="UnderstandingtheApplet"><FONT SIZE=5 COLOR=#Ff0000>Understanding the Applet</FONT></A></H2><P>By now, you should have a good idea of how classes work, at leastgenerally. Still, you'll now examine parts of Applet19's sourcecode. First, near the top of the source code is this line:<BLOCKQUOTE><PRE>import MyClass;</PRE></BLOCKQUOTE><P>Because the <TT>MyClass</TT> class is located in a different filethan Applet19, you need to tell Java where to find it. The aboveline tells Java that it can find everything it needs to know about<TT>MyClass</TT> in the <TT>MyClass.class</TT> file, which youcreated when you compiled <TT>MyClass.java</TT>.<P>The next line of interest is this one, which is located at thetop of Applet19's definition:<BLOCKQUOTE><PRE>MyClass myObject;</PRE></BLOCKQUOTE><P>This line tells Java that you'll be creating an object of the<TT>MyClass</TT> class and that the object will be called <TT>myObject</TT>.<P>At this point, you don't have the object created yet. You haveto create the object, which Applet19 does in its <TT>init()</TT>method, using the <TT>new</TT> operator, like this:<BLOCKQUOTE><PRE>myObject = new MyClass(1);</PRE></BLOCKQUOTE><P>After the above line executes, Java has created the object, whichmeans you can now call the object's public methods to manipulatethe object as appropriate. Objects of the <TT>MyClass</TT> classhave only two public methods (not counting the constructor). Applet19calls these methods in its <TT>paint()</TT> method, like this:<BLOCKQUOTE><PRE>myObject.SetField(value);value = myObject.GetField();</PRE></BLOCKQUOTE><P>In the first line, Applet19 calls the object's <TT>SetField()</TT>method, whose single argument is the value to which to set the<TT>myField</TT> data field. Due to its private access, this isthe only way to set the value of <TT>myField</TT> outside of theclass. If you tried to access <TT>myField</TT> with the line<BLOCKQUOTE><PRE>myObject.myField = value;</PRE></BLOCKQUOTE><P>you wouldn't even be able to compile the file. The compiler willgenerate an error telling you that you cannot access <TT>myField</TT>in this way (Figure 14.3).<P><A HREF="f14-3.gif"><B> Figure 14.3 : </B><I>The compiler complains when you ignore rules of access.</I></A><P><H2><A NAME="UsingInheritance"><FONT SIZE=5 COLOR=#Ff0000>Using Inheritance</FONT></A></H2><P>You may not know it, but throughout the second part of this book,you've been using inheritance to create your applets. Specifically,you've been deriving your applet classes (i.e, Applet10, Applet11,and so on) from Java's <TT>Applet</TT> superclass. By using inheritancein this way, you can take an existing class and create a new similarclass that does things a little differently. The new class willhave all the characteristics of its superclass, but will alsohave any new characteristics that you choose to add.<H3><A NAME="CreatingaSubclass">Creating a Subclass</A></H3><P>You derive a new class from a superclass by using the <TT>extends</TT>keyword, an apt name for a keyword because by deriving a new classyou usually extend the abilities of the original class. For example,when you create a new applet, you start the applet's class witha line that looks something like this:<BLOCKQUOTE><PRE>public class MyApplet extends Applet</PRE></BLOCKQUOTE><P>First, Java insists that all applet classes be declared as <TT>public</TT>.Next in the line, you can see the <TT>class</TT> keyword followedby the name of the class. Finally comes the <TT>extends</TT> keywordfollowed by the name of the superclass. In English, the aboveline means that the public class <TT>MyApplet</TT> is derivedfrom (is a subclass of) the existing <TT>Applet</TT> class. Asyou've probably already figured out, <TT>Applet</TT> is a classthat the Java makers created for you. This class contains allthe basic functionality you need to create an applet. You needonly extend (there's that word again) the specifics of the classin order to create your own applet class. Again, you've been doingthat in every applet you've written so far.<H3><A NAME="AddingFieldsandMethodstotheSubclass">Adding Fields and Methods to the Subclass</A></H3><P>One thing you can do when you create a subclass is to add yourown data fields and methods. For example, when you derive yourown applet class from Java's <TT>Applet</TT> class, although yourclass inherits tons of data fields and methods from the superclass,you'll undoubtedly need fields and methods not supplied in thesuperclass. Maybe your new applet is designed to play Tic-Tac-Toe.(Hmmmm. Where have I seen that before?) Obviously, when the fine
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -