⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch2.htm

📁 JAVA Developing Professional JavaApplets
💻 HTM
📖 第 1 页 / 共 5 页
字号:
method that dumps the current values to standard output.<BLOCKQUOTE><TT>class SimpleRecord {<BR>&nbsp;&nbsp;&nbsp;String firstName;<BR>&nbsp;&nbsp;&nbsp;String lastName;<BR>&nbsp;&nbsp;&nbsp;// Default constructor<BR>&nbsp;&nbsp;&nbsp;public SimpleRecord() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;firstName = &quot;&quot;;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lastName = &quot;&quot;;<BR>&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;// Constructor...<BR>&nbsp;&nbsp;&nbsp;public SimpleRecord(String firstName, String<BR>lastName) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.firstName = firstName;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.lastName = lastName;<BR>&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;&nbsp;// List the elements of the record...<BR>&nbsp;&nbsp;&nbsp;public void list() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;FirstName: &quot; + firstName);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;LastName: &quot; + lastName);<BR>&nbsp;&nbsp;&nbsp;}<BR>}</TT></BLOCKQUOTE><P>To instantiate the class with a name and dump its contents, usethe following:<BLOCKQUOTE><TT>SimpleRecord simple = new <BR>SimpleRecord(&quot;Thomas&quot;,&quot;Jefferson&quot;);<BR>simple.list();</TT></BLOCKQUOTE><P>You can use the <TT>extends</TT> operatorto <I>derive</I> from the SimpleRecord class a new class withadditional address information:<BLOCKQUOTE><TT>class AddressRecord extends SimpleRecord{<BR>&nbsp;&nbsp;&nbsp;String address;<BR>&nbsp;&nbsp;&nbsp;// Default constructor<BR>&nbsp;&nbsp;&nbsp;public AddressRecord() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;firstName = &quot;&quot;;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lastName = &quot;&quot;;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;address = &quot;&quot;;<BR>&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;&nbsp;// Constructor...<BR>&nbsp;&nbsp;&nbsp;public AddressRecord(String firstName, String<BR>lastName,<BR>&nbsp;&nbsp;&nbsp;&nbsp;String address) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.firstName = firstName;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.lastName = lastName;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.address = address;<BR>&nbsp;&nbsp;&nbsp;}<BR>}</TT></BLOCKQUOTE><P>Notice how this new AddressRecord class inherits the <TT>firstName</TT>and <TT>lastName</TT> variables fromthe SimpleRecord class. It also inherits the <TT>list()</TT>method. Therefore, if you call<BLOCKQUOTE><TT>record = new AddressRecord(&quot;Thomas&quot;,&quot;Jefferson&quot;,<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;Monticello&quot;);<BR>record.list();</TT></BLOCKQUOTE><P>you create a fully initialized AddressRecord object. However,the <TT>list()</TT> method printsonly the name variables because this call ultimately results incalling the SimpleRecord <TT>list()</TT>method. The reason for this is because you haven't explicitlydefined a <TT>list()</TT> method inthe AddressRecord. However, you can address this limitation throughmethod overriding.<H3><A NAME="MethodOverriding">Method Overriding</A></H3><P>Use <I>method overriding </I>when you need a subclass to replacea method of its superclass. Recall that each method has a signature.When you override a method, you are defining a new method thatreplaces the method in the superclass that has the same signature.Whenever you call a method, Java looks for a method of that signaturein the class definition of the object. If Java doesn't find themethod, it looks for a matching signature in the definition ofthe superclass. Java continues to look for the matching methoduntil it reaches the topmost superclass.<P>To add a <TT>list()</TT> method tothe AddressRecord class that displays the address, all you needto do is add this code to the class definition:<BLOCKQUOTE><TT>// List the elements of the record...<BR>&nbsp;&nbsp;&nbsp;public void list() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;FirstName: &quot; + firstName);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;LastName: &quot; + lastName);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Address:&quot; + address);<BR>&nbsp;&nbsp;&nbsp;}</TT></BLOCKQUOTE><P>The <TT>list()</TT> method call fromthe previous example will now print the following results:<BLOCKQUOTE><TT>First Name: Thomas<BR>Last Name: Jefferson<BR>Address: Monticello</TT></BLOCKQUOTE><H3><A NAME="CallingSuperclassMethods">Calling Superclass Methods</A></H3><P>You may have noticed that the AddressRecord <TT>list()</TT>method duplicates some code of the SimpleRecord <TT>list()</TT>method. Namely, it duplicates the following:<BLOCKQUOTE><TT>System.out.println(&quot;Last Name: &quot;+ lastName);<BR>System.out.println(&quot;Address: &quot; + address);</TT></BLOCKQUOTE><P>You can eliminate this redundancy. Recall that one of the pointsof inheritance is that a subclass takes an existing class andextends its definition. Because the <TT>list()</TT>method of SimpleRecord already has some of the behavior of theAddressRecord class, you should be able to use the SimpleRecord<TT>list()</TT> method as part ofthe base behavior of the AddressRecord class.<P>Use the <TT>super</TT> keyword torefer to a superclass. The <TT>super</TT>keyword is appropriate for the current problem being discussedbecause calling the superclass of AddressRecord has some of thebehavior the <TT>list()</TT> methodneeds. Consequently, the <TT>list()</TT>method of AddressRecord is modified to call the SimpleRecord <TT>list()</TT>method before specifying additional behavior:<BLOCKQUOTE><TT>public void list() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super.list();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Address:&quot; + address);<BR>&nbsp;&nbsp;&nbsp;}</TT></BLOCKQUOTE><P>This code now prints the full name and address, as mentioned inthe preceding section's definition of <TT>list()</TT>.<H3><A NAME="CallingSuperclassConstructors">Calling SuperclassConstructors</A></H3><P>You can use the <TT>super</TT> keywordto call the constructor of the superclass. The only differencefrom the previous use of <TT>super</TT>is that you call it without any method definition. For example,the two constructors of AddressRecord are modified to call theSimpleRecord constructor before performing its own initialization:<BLOCKQUOTE><TT>// Default constructor<BR>&nbsp;&nbsp;&nbsp;public AddressRecord() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;address = &quot;&quot;;<BR>&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;&nbsp;// Constructor...<BR>&nbsp;&nbsp;&nbsp;public AddressRecord(String firstName, String<BR>lastName,<BR>&nbsp;&nbsp;&nbsp;&nbsp;String address) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super(firstName,lastName);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.address = address;<BR>&nbsp;&nbsp;&nbsp;}</TT></BLOCKQUOTE><P>You can call the default constructor (no parameters) or anotherconstructor with <TT>super</TT> aslong as the constructor with the matching signature exists.<P>You can use the <TT>this</TT> keywordin a similar manner to call methods within your class. For example,suppose that you need a constructor that just adds an addressto the AddressRecord class, with the other fields set to emptystrings. You can do this by using the following code:<BLOCKQUOTE><TT>public AddressRecord(String address){<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.address = address;<BR>&nbsp;&nbsp;&nbsp;}</TT></BLOCKQUOTE><P>This code calls the default constructor of the AddressRecord class,which in turn calls the SimpleRecord default constructor. At thispoint, all the fields are set to empty strings. The code thenassigns the specified String to the address field, and you'reready to go.<P>You might wonder what the superclass of SimpleRecord is; the answeris in the next section.<H2><A NAME="ImportantCoreClasses"><FONT SIZE=5 COLOR=#FF0000>ImportantCore Classes</FONT></A></H2><P>Now that you have seen the fundamentals of classes in Java, it'stime to see how some of the basic classes in Java work. Becausethese classes are used throughout Java, you should be familiarwith them.<H3><A NAME="TheObjectBaseClass">The Object Base Class</A></H3><P>The Object class is <I>the</I> base class of all classes in Java-theultimate superclass of all classes. Because of its primary nature,the methods of the Object class are present in all other classes,although custom methods often override them.<P>The Object class has a variety of interesting methods. Each Objecthas its own String representation. This may be a system-generatedname or something generated by the class. For example, a Stringobject's representation is the string itself. You get an Object'sString representation in two ways:<BLOCKQUOTE><TT>Object o = new Object();<BR>System.out.println(&quot;Object = &quot; + o);<BR>System.out.println(&quot;Object = &quot; + o.toString());</TT></BLOCKQUOTE><P>In the second line of the preceding example, the Object itselfis provided as part of the printout. The Object's <TT>toString()</TT>method is actually called when an Object is provided as part ofthe <TT>print</TT> statement. Consequently,the second and third lines are functionally equivalent. The <TT>toString()</TT>method should be overridden if you want a custom String representation;it is overriden throughout the Java class libraries.<P>The <TT>finalize()</TT> method isthe closest thing Java objects have to a destroy method. Recallthat Java has automatic memory management so you don't have toexplicitly delete objects. The <I>garbage collector</I> removesunreferenced objects from memory. When an object is about to get&quot;garbage collected,&quot; its <TT>finalize()</TT>method is called. This can be overridden if you need to do somecustom cleanup, such as closing a file or terminating a connection.However, because garbage collection doesn't happen at predictabletimes, you need to use the <TT>finalize()</TT>method carefully. You can also call the method manually, as inright before removing a reference.<P>Each class in Java has a class <I>descriptor</I>. The Class classrepresents this descriptor, which you access by using the <TT>getClass()</TT>method of the Object class. You cannot modify the returned classdescriptor. However, you can use it to get all kinds of usefulinformation. For example, the <TT>getSuperclass()</TT>method returns the class descriptor of a class's superclass. Forexample, to get the superclass of a String, you can call the following:<BLOCKQUOTE><TT>String s = &quot;A string&quot;;<BR>System.out.println(&quot;String superclass = &quot; +<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s.getClass().getSuperclass());</TT></BLOCKQUOTE><P>The <TT>getName()</TT> method of Classreturns the name of the class.<P>You may notice the <TT>wait()</TT>and <TT>notify()</TT> methods of theObject class. These are complex methods related to threaded processing,which is discussed in detail in <A HREF="ch8.htm" >Chapter 8</A>,&quot;Adding Threads to Applets.&quot;<H3><A NAME="StringClasses">String Classes</A></H3><P>As stated in <A HREF="ch1.htm" >Chapter 1</A>, <I>string literals</I>are implemented as objects of the String class. You can createstrings in a variety of ways. First, you can assign a String toa literal, as has been shown. You can also use String arithmeticto concatenate one String to another. For example, the secondstring in<BLOCKQUOTE><TT>String s1 = &quot;A string&quot;;<BR>String s2 = s1 + &quot; with some additional text&quot;;</TT></BLOCKQUOTE><P>is set to <TT>&quot;A string with some additionaltext&quot;</TT>. You can also use other operators, suchas <TT>+=</TT>, in String arithmetic.String concatenation also works with primitive data types. Forexample, this is a valid operation:<BLOCKQUOTE><TT>String s = &quot;This is number &quot;+ 6;</TT></BLOCKQUOTE><P>Although you cannot change String objects after creating them,you can apply methods to them to yield new String objects. Forexample, you can use the <TT>substring()</TT>method to return a String starting at a specific index. You canalso apply other operations. The <TT>length()</TT>method returns the length of the String. For example, the followingmethods applied on the above String objects print <TT>withsome additional text</TT>:<BLOCKQUOTE><TT>System.out.println(s2.substring(s1.length()));</TT></BLOCKQUOTE><P>A series of overloaded <TT>valueOf()</TT>methods is particularly useful. These methods take a primitive

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -