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

📄 tij308.htm

📁 这也是我们java老师给我们的thinking in java的一些资料
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en">
<!--
This document was converted from RTF source: 
By r2net 5.8 r2netcmd Windows 
See http://www.logictran.com
-->
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Thinking in Java, 3rd ed. Revision 4.0: 6: Reusing Classes</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css"></head>

<body >
   <CENTER>     <a href="http://www.MindView.net">     <img src="mindview.gif" alt="MindView Inc." BORDER = "0"></a>     <Font FACE="Verdana, Tahoma, Arial, Helvetica, Sans">     <h2>Thinking in Java, 3<sup>rd</sup> ed. Revision 4.0</h2>     <FONT size = "-1"><br>     [ <a href="README.txt">Viewing Hints</a> ]     [ <a href="http://www.mindview.net/Books/TIJ/">Book Home Page</a> ]     [ <a href="http://www.mindview.net/Etc/MailingList.html">Free Newsletter</a> ] <br>     [ <a href="http://www.mindview.net/Seminars">Seminars</a> ]     [ <a href="http://www.mindview.net/CDs">Seminars on CD ROM</a> ]     [ <a href="http://www.mindview.net/Services">Consulting</a> ] <br><br>     </FONT></FONT>   </CENTER> 
<font face="Georgia"><div align="CENTER"><a href="TIJ307.htm" target="RightFrame"><img src="./prev.gif" alt="Previous " border="0"></a>
<a href="TIJ309.htm" target="RightFrame"><img src="./next.gif" alt="Next " border="0"></a>

<a href="TIJ3_t.htm"><img src="./first.gif" alt="Title Page " border="0"></a>
<a href="TIJ3_i.htm"><img src="./index.gif" alt="Index " border="0"></a>
<a href="TIJ3_c.htm"><img src="./contents.gif" alt="Contents " border="0"></a>
</div>
<hr>

<h1>
<a name="_Toc375545305"></a><a name="_Toc24272645"></a><a name="_Toc24775634"></a><a name="Heading5039"></a>6:
Reusing Classes</h1>
<p class="Intro">One of the most compelling features about Java is code reuse. But to be revolutionary, you&#146;ve got to be able to do a lot more than copy code and change it.<br></p>
<p><a name="Index483"></a><a name="Index484"></a>That&#146;s the approach used in procedural languages like C, and it hasn&#146;t worked very well. Like everything in Java, the solution revolves around the class. You reuse code by creating new classes, but instead of creating them from scratch, you use existing classes that someone has already built and debugged. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_911" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>The trick is to use the classes without soiling the existing code. In this chapter you&#146;ll see two ways to accomplish this. The first is quite straightforward: you simply create objects of your existing class inside the new class. This is called <i>composition,</i> because the new class is composed of objects of existing classes. You&#146;re simply reusing the functionality of the code, not its form. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_912" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p><a name="Index485"></a>The second approach is more subtle. It creates a new class as a <i>type of</i> an existing class. You literally take the form of the existing class and add code to it without modifying the existing class. This magical act is called <i>inheritance</i><a name="Index486"></a>, and the compiler does most of the work. Inheritance is one of the cornerstones of object-oriented programming, and has additional implications that will be explored in Chapter 7. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_913" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>It turns out that much of the syntax and behavior are similar for both composition and inheritance (which makes sense because they are both ways of making new types from existing types). In this chapter, you&#146;ll learn about these code reuse mechanisms. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_914" title="Send BackTalk Comment">Feedback</a></font><br></p>
<h2>
<a name="_Toc305593251"></a><a name="_Toc305628723"></a><a name="_Toc312374014"></a><a name="_Toc375545306"></a><a name="_Toc24775635"></a><a name="Heading5045"></a>Composition
syntax</h2>
<p>Until now, composition has been used quite frequently. You simply place object references inside new classes. For example, suppose you&#146;d like an object that holds several <b>String</b> objects, a couple of primitives, and an object of another class. For the nonprimitive objects, you put references inside your new class, but you define the primitives directly:<br></p>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c06:SprinklerSystem.java</font>
<font color=#009900>// Composition for code reuse.</font>
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;

<font color=#0000ff>class</font> WaterSource {
  <font color=#0000ff>private</font> String s;
  WaterSource() {
    System.out.println(<font color=#004488>"WaterSource()"</font>);
    s = <font color=#0000ff>new</font> String(<font color=#004488>"Constructed"</font>);
  }
  <font color=#0000ff>public</font> String toString() { <font color=#0000ff>return</font> s; }
}

<font color=#0000ff>public</font> <font color=#0000ff>class</font> SprinklerSystem {
  <font color=#0000ff>private</font> <font color=#0000ff>static</font> Test monitor = <font color=#0000ff>new</font> Test();
  <font color=#0000ff>private</font> String valve1, valve2, valve3, valve4;
  <font color=#0000ff>private</font> WaterSource source;
  <font color=#0000ff>private</font> <font color=#0000ff>int</font> i;
  <font color=#0000ff>private</font> <font color=#0000ff>float</font> f;
  <font color=#0000ff>public</font> String toString() {
    <font color=#0000ff>return</font>
      <font color=#004488>"valve1 = "</font> + valve1 + <font color=#004488>"\n"</font> +
      <font color=#004488>"valve2 = "</font> + valve2 + <font color=#004488>"\n"</font> +
      <font color=#004488>"valve3 = "</font> + valve3 + <font color=#004488>"\n"</font> +
      <font color=#004488>"valve4 = "</font> + valve4 + <font color=#004488>"\n"</font> +
      <font color=#004488>"i = "</font> + i + <font color=#004488>"\n"</font> +
      <font color=#004488>"f = "</font> + f + <font color=#004488>"\n"</font> +
      <font color=#004488>"source = "</font> + source;
  }
  <font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
    SprinklerSystem sprinklers = <font color=#0000ff>new</font> SprinklerSystem();
    System.out.println(sprinklers);
    monitor.expect(<font color=#0000ff>new</font> String[] {
      <font color=#004488>"valve1 = null"</font>,
      <font color=#004488>"valve2 = null"</font>,
      <font color=#004488>"valve3 = null"</font>,
      <font color=#004488>"valve4 = null"</font>,
      <font color=#004488>"i = 0"</font>,
      <font color=#004488>"f = 0.0"</font>,
      <font color=#004488>"source = null"</font>
    });
  }
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>One of the methods defined in both classes is special: <b>toString(&#160;)</b>. You will learn later that every nonprimitive object has a <a name="Index487"></a><a name="Index488"></a><b>toString(&#160;)</b> method, and it&#146;s called in special situations when the compiler wants a <b>String</b> but it has an object. So in the expression in <b>SprinklerSystem.toString(&#160;)</b>:<br></p>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#004488>"source = "</font> + source;</PRE></FONT></BLOCKQUOTE><p><br></p>
<p>the compiler sees you trying to add a <b>String</b> object ("<b>source = </b>") to a <b>WaterSource</b>. Because you can only &#147;add&#148; a <b>String</b> to another <b>String</b>, it says &#147;I&#146;ll turn <b>source</b> into a <b>String</b> by calling <b>toString(&#160;)</b>!&#148; After doing this it can combine the two <b>String</b>s and pass the resulting <b>String</b> to <b>System.out.println(&#160;)</b>. Any time you want to allow this behavior with a class you create, you need only write a <b>toString(&#160;)</b> method.  <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_915" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p><a name="Index489"></a><a name="Index490"></a>Primitives that are fields in a class are automatically initialized to zero, as noted in Chapter 2. But the object references are initialized to <a name="Index491"></a><a name="Index492"></a><b>null</b>, and if you try to call methods for any of them, you&#146;ll get an exception. It&#146;s actually good (and useful) that you can still print them out without throwing an exception. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_916" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>It makes sense that the compiler doesn&#146;t just create a default object for every reference, because that would incur unnecessary overhead in many cases. If you want the references initialized, you can do it: <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_917" title="Send BackTalk Comment">Feedback</a></font><br></p>
<ol>
<li>At the point the objects are defined. This means that they&#146;ll always
be initialized before the constructor is called. <font size="-2"><a
href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_918" title="Send BackTalk
Comment">Feedback</a></font></li>
<li>In the constructor for that class. <font size="-2"><a
href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_919" title="Send BackTalk
Comment">Feedback</a></font></li>
<li>Right before you actually need to use the object. This is often called
<i>lazy initialization</i><a name="Index493"></a><a name="Index494"></a>. It can
reduce overhead in situations where object creation is expensive and the object
doesn&#146;t need to be created every time. <font size="-2"><a
href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_920" title="Send BackTalk
Comment">Feedback</a></font></li></ol><p>All three approaches are shown here: <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap06_921" title="Send BackTalk Comment">Feedback</a></font><br></p>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c06:Bath.java</font>
<font color=#009900>// Constructor initialization with composition.</font>
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;

<font color=#0000ff>class</font> Soap {
  <font color=#0000ff>private</font> String s;
  Soap() {
    System.out.println(<font color=#004488>"Soap()"</font>);
    s = <font color=#0000ff>new</font> String(<font color=#004488>"Constructed"</font>);
  }
  <font color=#0000ff>public</font> String toString() { <font color=#0000ff>return</font> s; }
}

<font color=#0000ff>public</font> <font color=#0000ff>class</font> Bath {
  <font color=#0000ff>private</font> <font color=#0000ff>static</font> Test monitor = <font color=#0000ff>new</font> Test();
  <font color=#0000ff>private</font> String <font color=#009900>// Initializing at point of definition:</font>
    s1 = <font color=#0000ff>new</font> String(<font color=#004488>"Happy"</font>),
    s2 = <font color=#004488>"Happy"</font>,
    s3, s4;
  <font color=#0000ff>private</font> Soap castille;
  <font color=#0000ff>private</font> <font color=#0000ff>int</font> i;
  <font color=#0000ff>private</font> <font color=#0000ff>float</font> toy;
  <font color=#0000ff>public</font> Bath() {
    System.out.println(<font color=#004488>"Inside Bath()"</font>);
    s3 = <font color=#0000ff>new</font> String(<font color=#004488>"Joy"</font>);
    i = 47;
    toy = 3.14f;
    castille = <font color=#0000ff>new</font> Soap();
  }
  <font color=#0000ff>public</font> String toString() {
    <font color=#0000ff>if</font>(s4 == <font color=#0000ff>null</font>) <font color=#009900>// Delayed initialization:</font>
      s4 = <font color=#0000ff>new</font> String(<font color=#004488>"Joy"</font>);
    <font color=#0000ff>return</font>
      <font color=#004488>"s1 = "</font> + s1 + <font color=#004488>"\n"</font> +
      <font color=#004488>"s2 = "</font> + s2 + <font color=#004488>"\n"</font> +
      <font color=#004488>"s3 = "</font> + s3 + <font color=#004488>"\n"</font> +
      <font color=#004488>"s4 = "</font> + s4 + <font color=#004488>"\n"</font> +
      <font color=#004488>"i = "</font> + i + <font color=#004488>"\n"</font> +
      <font color=#004488>"toy = "</font> + toy + <font color=#004488>"\n"</font> +
      <font color=#004488>"castille = "</font> + castille;

⌨️ 快捷键说明

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