📄 ch14.htm
字号:
<HTML><HEAD><TITLE>developer.com - Reference</TITLE><META NAME="Author" CONTENT="developer.com"><META NAME="Keywords" CONTENT="javascript, ActiveX, VRML, Push, channel,push channel, applet, directory, news, community, developer, internet,intranet, java, java applet, J++, javabeans, java products, tools, javatools, JDK, java development kit, java development environment, JIT,JavaPlan, enterprise tools, JVM, Java Virtual Machine, Java resources, API,browser, java documentation, CDF, Common Desktop Format, RDF, ResourceDescription Framework, Netcaster, Netcast, Castanet, meta-language, metadata,solaris, Solaris, SUN, CGI, Perl, Oracle, database, network, Netscape API,Apache, apache, SSL, mSQL, Netscape, Fasttrack, FastTrack,industry standard, ActiveX bridge, web, internet, site, sitedesign, microsoft, active server pages, asp, iis, nt, win95, 95, html, cgi,frontpage, business, corporate, vbscript, javascript, activex, isapi,database, access, sql, server, www, 3.0, 3.01, 3.02, 3.03, 3.04, 4.0,4.0b2, 4.01, 4.03, 4.04, connection, online, commerce, publisher,publishing, publish, webmaster, dynamic html, dhtml, windows 98, netscape,netscape software, shareware, magazines, jobs, japan, free, freeware, freestuff"><META NAME="description" CONTENT="Developer.com is the leading onlineservice for developers. It includes Gamelan, the official directory for Java, as wellas news, information, tutorials, and directories for other Internet technologiesincluding ActiveX, JavaScript, perl, VRML, Java Beans, push technologies, andother Internet and intranet technologies. Developer.com is also the home ofDeveloper Direct, the Professional Developer's Store, where developers canpurchase and download thousands of Web, authoring and other developmentproducts at some of today's lowest prices."><META NAME="distribution" CONTENT="global"><META NAME="resource-type" CONTENT="document"><META NAME="language" CONTENT="en"></HEAD><BODY BACKGROUND="/images/curve_r-wide.gif" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#DD0000" VLINK="#999999" ALINK="#FF0000"><TABLE><TR><TD VALIGN=TOP WIDTH=120><A HREF="/" ><IMG SRC="/images/masthead_r.gif" WIDTH="100" HEIGHT="78" BORDER="0"ALT="Developer.com Logo"></a></TD><TD><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCBAN.REF/DT=null"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCBAN.REF/DT=null" HEIGHT="60" WIDTH="468" ALT="Click here to support our advertisers"><BR><CENTER>Click here to support our advertisers</CENTER></a></TD></TR></TABLE><!--outer table--><TABLE><!--outer table--><TR><!--outer table--><TD VALIGN="TOP"><!--navbar info --><table><tr><td><A HREF="http://www.developerdirect.com/" ><IMG SRC="/images/button_s.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>SHOPPING</b></font></a></td></tr><tr><td><A HREF="/community/jobs/c_jobs.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>JOB BANK</B></font></a></td></tr><tr><td><A HREF="http://www.classifieds2000.com/cgi-cls/display.exe?Developer+computer+searchcomputercategories"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>CLASSIFIEDS</B></font></a></td></tr><tr><td><A HREF="/directories/directories.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>DIRECTORIES</B></font></a></td></tr><tr><td><A HREF="/reference/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>REFERENCE</B></font></a><br><a href="/reference/r_library.html"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">Online Library</a></font></td></tr><tr><td><A HREF="/classroom/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>LEARNING CENTER</B></font></a></td></tr><tr><td><A HREF="/journal/"><IMG SRC="/images/button_n.gif" width="15" height="11" BORDER="0"><B><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">JOURNAL</font></B></a></td></tr><tr><td><A HREF="/news/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>NEWS CENTRAL</b></font></a></td></tr><tr><td><A HREF="/downloads/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>DOWNLOADS</b></font></a></td></tr><tr><td><A HREF="/community/" ><IMG SRC="/images/button_c.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>COMMUNITY</B></font></a></td></tr><tr><td><A HREF="/calendar/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>CALENDAR</b></font></a></td></tr><tr><td><A HREF="/about/"><IMG SRC="/images/button_a.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>ABOUT US</b></a></font></td></tr></table><table><tr><td><form action="/subscribe/list.cgi" method=post ><img src="/images/rule.gif" width="100" height="2"><br><B><FONT FACE="Arial, Helvetica" SIZE="-1">Journal:</b></font><br><input name='email' value='your e-mail' size="11"><input type='hidden' name='state' value='Subscribe'></td></tr><tr><td><input type='submit' value='Subscribe'><br><font size="-1">Get the weekly email highlights from the most popular journal for developers!<br><a href="http://www.developer.com/subscribe.html">Current issue</a><img src="/images/rule.gif" width="100" height="2"><input type='hidden' name='name' value='New Subscriber'></FORM></td></tr></table><!--/navbar--><font size="-1"><A HREF="http://www.developer.com">developer.com</a><BR><A HREF="http://www.developerdirect.com">developerdirect.com</a><BR><A HREF="http://www.htmlgoodies.com">htmlgoodies.com</a><BR><A HREF="http://www.javagoodies.com">javagoodies.com</a><br><A HREF="http://www.jars.com">jars.com</a><BR><a href="http://www.intranetjournal.com">intranetjournal.com</a><br><a href="http://www.javascripts.com">javascripts.com</a><br></font><!--outer table--></TD><!--outer table--><TD VALIGN="TOP"><BLOCKQUOTE><P><img src="/images/header_r.gif" width="440" height="50"><P><MAP NAME ="header_r2.gif.map"><AREA SHAPE ="RECT" HREF ="/reference/author.html" COORDS ="361,0,440,29"><AREA SHAPE ="RECT" HREF ="/reference/basic.html" COORDS ="254,0,360,29"><AREA SHAPE ="RECT" HREF ="/reference/help.html" COORDS ="183,0,251,29"><AREA SHAPE ="RECT" HREF ="/reference/cool.html" COORDS ="100,0,181,29"><AREA SHAPE ="RECT" HREF ="/reference/mybook.html" COORDS ="0,0,100,29"></MAP><MAP NAME ="header_r1.gif.map"><AREA SHAPE ="RECT" HREF ="/reference/personalize.html" COORDS ="339,0,439,29"></MAP><p><font face="Arial,Helvetica" size="-1" color="#006666"><A HREF="/reference/r_library.html"><B>All Categories</A> :</B><b><A HREF="/reference/r_java.html">Java</A></b></font><p><META><H1><FONT SIZE=6 COLOR=#Ff0000>Chapter 14</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>Classes</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#ClassesandObjects">Classes and Objects</A><UL><LI><A HREF="#DefiningaSimpleClass">Defining a Simple Class</A><LI><A HREF="#DeclaringFieldsforaClass">Declaring Fields for a Class</A><LI><A HREF="#DefiningaConstructor">Defining a Constructor</A><LI><A HREF="#ExampleCreatinganObjectbyCallingaConstructor">Example: Creating an Object by Calling a Constructor</A><LI><A HREF="#DefiningMethods">Defining Methods</A></UL><LI><A HREF="#ExampleUsingClassesinApplets">Example: Using Classes in Applets</A><LI><A HREF="#UnderstandingtheApplet">Understanding the Applet</A><LI><A HREF="#UsingInheritance">Using Inheritance</A><UL><LI><A HREF="#CreatingaSubclass">Creating a Subclass</A><LI><A HREF="#AddingFieldsandMethodstotheSubclass">Adding Fields and Methods to the Subclass</A><LI><A HREF="#ExampleAddingFieldsandMethods">Example: Adding Fields and Methods</A></UL><LI><A HREF="#ExampleUsingaSubclassinaProgram">Example: Using a Subclass in a Program</A><LI><A HREF="#OverridingMethodsoftheSuperclass">Overriding Methods of the Superclass</A><LI><A HREF="#TheIthisIKeyword">The <I>this</I> Keyword</A><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>Way back in <A HREF="ch4.htm" >Chapter 4</A> you got a general introduction to object-orientedprogramming concepts. In that chapter, you took a first look atclasses and how they're used to organize source code into logicallydefined modules. Since then, you've been using various classesincluded as part of the Java language, but you haven't exploredthe implications of using a class or of creating your own classes.In this chapter, you plug up that hole in your understanding ofJava and how it uses classes to create applets.<H2><A NAME="ClassesandObjects"><FONT SIZE=5 COLOR=#Ff0000>Classes and Objects</FONT></A></H2><P>In <A HREF="ch4.htm" >Chapter 4</A> you learned that a class is the template for anobject and that a class is a way to encapsulate both data (calledfields in Java) and the functions (called methods) that operateon that data. You also learned about inheritance, which enablesa class (called the subclass) to inherit the capabilities of abase class (called a superclass in Java). Finally, you discoveredthat polymorphism enables you to create virtual methods that canbe implemented differently in derived classes. In this section,you'll apply what you know about object-oriented programming towardscreating Java classes.<H3><A NAME="DefiningaSimpleClass">Defining a Simple Class</A></H3><P>As I said, a class is sort of a template for an object. In thisway, a class is equivalent to a data type such as <TT>int</TT>.The main difference is that Java already knows what an integeris. However, when you create a class, you must tell Java aboutthe class's characteristics. You define a class by using the <TT>class</TT>keyword along with the class name, like this:<BLOCKQUOTE><PRE>class MyClass{}</PRE></BLOCKQUOTE><P>Believe it or not, the preceding lines are a complete Java class.If you save the lines in a file called <TT>MyClass.java</TT>,you could even compile the class into a .CLASS file, althoughthe file won't actually do anything if you tried to run it. Asyou can see, the class definition begins with the keyword <TT>class</TT>followed by the name of the class. The body of the class is markedoff by curly braces just like any other program block. In thiscase, the class's body is empty.<P>Because its body is empty, this example class doesn't do anything.You can, however, compile the class and even create an objectfrom it. To create an object from a class, you type the class'sname followed by the name of the object. For example, the linebelow creates an object from the <TT>MyClass</TT> class:<BLOCKQUOTE><PRE>MyClass myObject = new MyClass();</PRE></BLOCKQUOTE><H3><A NAME="DeclaringFieldsforaClass">Declaring Fields for a Class</A></H3><P>As I said, the <TT>MyClass</TT> example class doesn't do muchyet. In order to be useful, it needs both data fields and methods.You declare fields for your class in much the same way you declareany variable in a program, by typing the data type of the fieldfollowed by the name of the field, like this:<BLOCKQUOTE><PRE>int myField;</PRE></BLOCKQUOTE><P>The above line declares a data field of type integer. However,looking at the above line doesn't tell you much about how datafields are used with classes. In fact, you can't tell from theabove line whether <TT>myField</TT> is actually part of an objector just a normal variable. To clear up this ambiguity, you canplug the above line into the <TT>MyClass</TT> class definition,as shown in Listing 14.1.<HR><BLOCKQUOTE><B>Listing 14.1 LST14_1.TXT: Adding a Data Field toa Class.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>class MyClass{ int myField;}</PRE></BLOCKQUOTE><HR><P>Now you can see that <TT>myField</TT> is a data field of the <TT>MyClass</TT>class. Moreover, this data field is by default accessible onlyby methods in the same package. (For now, you can think of a packageas a file.) You can change the rules of this access by using the<TT>public</TT>, <TT>protected</TT>, and <TT>private</TT> keywords.A <TT>public</TT> data field can be accessed by any part of aprogram, inside or outside of the class in which it's defined.A <TT>protected</TT> data field can only be accessed from withinthe class or from within a derived class (a subclass). A <TT>private</TT>data field cannot even be accessed by a derived class.<H3><A NAME="DefiningaConstructor">Defining a Constructor</A></H3><P>You have now added a data field to <TT>MyClass</TT>. However,the class has no methods and so can do nothing with its data field.The next step in defining the class, then, is to create methods.One special type of method, called a constructor, enables an objectto initialize itself when it's created. A constructor is a <TT>public</TT>method (a method that can be accessed anywhere in a program) withthe same name as the class. Listing 14.2 shows the <TT>MyClass</TT>class with its constructor in place.<HR><BLOCKQUOTE><B>Listing 14.2 LST14_2.TXT: Adding a Constructor toa Class.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>class MyClass{ int myField; public MyClass(int value) { myField = value; }}</PRE></BLOCKQUOTE><HR><P>As you can see, the class's constructor starts with the <TT>public</TT>keyword. This is important because you want to be able to createan object from the class anywhere in your program, and when youcreate an object, you're actually calling its constructor. Afterthe <TT>public</TT> keyword comes the name of the constructorfollowed by the constructor's arguments in parentheses. When youcreate an object of the class, you must also provide the requiredarguments.<H3><A NAME="ExampleCreatinganObjectbyCallingaConstructor">Example: Creating an Object by Calling a Constructor</A></H3><P>If you want to create an object from <TT>MyClass</TT>, you mustsupply an integer value that the class uses to initialize the<TT>myField</TT> data field. This integer is the <TT>MyClass</TT>constructor's single argument. You'd create an object of the classlike this:<BLOCKQUOTE><PRE>MyClass myObject = new MyClass(1);</PRE></BLOCKQUOTE><P>This line not only creates an object of the <TT>MyClass</TT> class,but also initializes the <TT>myField</TT> data field to 1. Thefirst word in the line tells Java that <TT>myObject</TT> is goingto be an object of the <TT>MyClass</TT> class. The next word isthe object's name. After the equals sign comes the keyword <TT>new</TT>and the call to the class's constructor.<H3><A NAME="DefiningMethods">Defining Methods</A></H3><P>Other methods that you add to a class are just like the methodsyou've been writing in previous chapters. You just need to besure to provide the proper type of access to your methods. Thatis, methods that must be called from outside the class, should
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -