📄 tij306.htm
字号:
<!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: 4: Initialization & Cleanup</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="TIJ305.htm" target="RightFrame"><img src="./prev.gif" alt="Previous " border="0"></a>
<a href="TIJ307.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="_Toc375545274"></a><a name="_Toc24272643"></a><a name="_Toc24775599"></a><a name="Heading3344"></a>4:
Initialization <br>& Cleanup</h1>
<p class="Intro">As the computer revolution progresses, “unsafe” programming has become one of the major culprits that makes programming expensive.<br></p>
<p>Two of these safety issues are <i>initialization</i> and <i>cleanup</i>. Many C bugs occur when the programmer forgets to initialize a variable. This is especially true with libraries when users don’t know how to initialize a library component, or even that they must. Cleanup is a special problem because it’s easy to forget about an element when you’re done with it, since it no longer concerns you. Thus, the resources used by that element are retained and you can easily end up running out of resources (most notably, memory). <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_647" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>C++ introduced the concept of a <i>constructor</i>, a special method automatically called when an object is created. Java also adopted the constructor, and in addition has a garbage collector that automatically releases memory resources when they’re no longer being used. This chapter examines the issues of initialization and cleanup, and their support in Java. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_648" title="Send BackTalk Comment">Feedback</a></font><br></p>
<h2>
<a name="_Toc312373853"></a><a name="_Toc375545275"></a><a name="_Toc24775600"></a><a name="Heading3348"></a>Guaranteed
initialization <br>with the constructor</h2>
<p>You can imagine creating a method called <b>initialize( )</b> for every class you write. The name is a hint that it should be called before using the object. Unfortunately, this means the user must remember to call the method. In Java, the class designer can guarantee initialization of every object by providing a special method called a <i>constructor</i>. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_649" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p><a name="Index324"></a><a name="Index325"></a>The next challenge is what to name this method. There are two issues. The first is that any name you use could clash with a name you might like to use as a member in the class. The second is that because the compiler is responsible for calling the constructor, it must always know which method to call. The C++ solution seems the easiest and most logical, so it’s also used in Java: The name of the constructor is the same as the name of the class. It makes sense that such a method will be called automatically on initialization. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_650" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p><a name="Index326"></a>Here’s a simple class with a constructor:<br></p>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c04:SimpleConstructor.java</font>
<font color=#009900>// Demonstration of a simple constructor.</font>
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;
<font color=#0000ff>class</font> Rock {
Rock() { <font color=#009900>// This is the constructor</font>
System.out.println(<font color=#004488>"Creating Rock"</font>);
}
}
<font color=#0000ff>public</font> <font color=#0000ff>class</font> SimpleConstructor {
<font color=#0000ff>static</font> Test monitor = <font color=#0000ff>new</font> Test();
<font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < 10; i++)
<font color=#0000ff>new</font> Rock();
monitor.expect(<font color=#0000ff>new</font> String[] {
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>,
<font color=#004488>"Creating Rock"</font>
});
}
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>Now, when an object is created: <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_651" title="Send BackTalk Comment">Feedback</a></font><br></p>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#0000ff>new</font> Rock();</PRE></FONT></BLOCKQUOTE><p><br></p>
<p>storage is allocated and the constructor is called. It is guaranteed that the object will be properly initialized before you can get your hands on it. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_652" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>Note that the coding style of making the first letter of all methods lowercase does not apply to constructors, since the name of the constructor must match the name of the class <i>exactly</i>. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_653" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>Like any method, the constructor can have arguments to allow you to specify <a name="Index328"></a><a name="Index329"></a><i>how</i> an object is created. The preceding example can easily be changed so the constructor takes an argument:<br></p>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c04:SimpleConstructor2.java</font>
<font color=#009900>// Constructors can have arguments.</font>
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;
<font color=#0000ff>class</font> Rock2 {
Rock2(<font color=#0000ff>int</font> i) {
System.out.println(<font color=#004488>"Creating Rock number "</font> + i);
}
}
<font color=#0000ff>public</font> <font color=#0000ff>class</font> SimpleConstructor2 {
<font color=#0000ff>static</font> Test monitor = <font color=#0000ff>new</font> Test();
<font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < 10; i++)
<font color=#0000ff>new</font> Rock2(i);
monitor.expect(<font color=#0000ff>new</font> String[] {
<font color=#004488>"Creating Rock number 0"</font>,
<font color=#004488>"Creating Rock number 1"</font>,
<font color=#004488>"Creating Rock number 2"</font>,
<font color=#004488>"Creating Rock number 3"</font>,
<font color=#004488>"Creating Rock number 4"</font>,
<font color=#004488>"Creating Rock number 5"</font>,
<font color=#004488>"Creating Rock number 6"</font>,
<font color=#004488>"Creating Rock number 7"</font>,
<font color=#004488>"Creating Rock number 8"</font>,
<font color=#004488>"Creating Rock number 9"</font>
});
}
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>Constructor arguments provide you with a way to provide parameters for the initialization of an object. For example, if the class <b>Tree</b> has a constructor that takes a single integer argument denoting the height of the tree, you would create a <b>Tree</b> object like this: <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_654" title="Send BackTalk Comment">Feedback</a></font><br></p>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>Tree t = <font color=#0000ff>new</font> Tree(12); <font color=#009900>// 12-foot tree</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>If <b>Tree(int)</b> is your only constructor, then the compiler won’t let you create a <b>Tree</b> object any other way. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_655" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>Constructors eliminate a large class of problems and make the code easier to read. In the preceding code fragment, for example, you don’t see an explicit call to some <b>initialize( )</b> method that is conceptually separate from creation. In Java, creation and initialization are unified concepts—you can’t have one without the other. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_656" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>The constructor is an unusual type of method because it has no return value. This is distinctly different from a <a name="Index330"></a><a name="Index331"></a><b>void</b> return value, in which the method returns nothing but you still have the option to make it return something else. Constructors return nothing and you don’t have an option (the <b>new</b> expression does return a reference to the newly-created object, but the constructor itself has no return value). If there were a return value, and if you could select your own, the compiler would somehow need to know what to do with that return value. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_657" title="Send BackTalk Comment">Feedback</a></font><br></p>
<h2>
<a name="_Toc375545276"></a><a name="_Toc24775601"></a><a name="Heading3424"></a>Method
overloading<br></h2>
<p><a name="Index332"></a><a name="Index333"></a>One of the important features in any programming language is the use of names. When you create an object, you give a name to a region of storage. A method is a name for an action. By using names to describe your system, you create a program that is easier for people to understand and change. It’s a lot like writing prose—the goal is to communicate with your readers. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_658" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>You refer to all objects and methods by using names. Well-chosen names make it easier for you and others to understand your code. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_659" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>A problem arises when mapping the concept of nuance in human language onto a programming language. Often, the same word expresses a number of different meanings—it’s <i>overloaded</i>. This is useful, especially when it comes to trivial differences. You say “wash the shirt,” “wash the car,” and “wash the dog.” It would be silly to be forced to say, “shirtWash the shirt,” “carWash the car,” and “dogWash the dog” just so the listener doesn’t need to make any distinction about the action performed. Most human languages are redundant, so even if you miss a few words, you can still determine the meaning. We don’t need unique identifiers—we can deduce meaning from context. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_660" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>Most programming languages (C in particular) require you to have a unique identifier for each function. So you could not have one function called <b>print( )</b> for printing integers and another called <b>print( )</b> for printing floats—each function requires a unique name. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_661" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>In Java (and C++), another factor forces the overloading of method names: the constructor. Because the constructor’s name is predetermined by the name of the class, there can be only one constructor name. But what if you want to create an object in more than one way? For example, suppose you build a class that can initialize itself in a standard way or by reading information from a file. You need two constructors, one that takes no arguments (the <a name="Index334"></a><a name="Index335"></a><i>default</i> constructor,<sup><a name="fnB19" href="#fn19">[19]</a></sup> also called the <i>no-arg</i> constructor), and one that takes a <b>String</b> as an argument, which is the name of the file from which to initialize the object. Both are constructors, so they must have the same name—the name of the class. Thus, <i>method overloading</i> is essential to allow the same method name to be used with different argument types. And although method overloading is a must for constructors, it’s a general convenience and can be used with any method. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap04_662" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>Here’s an example that shows both overloaded constructors and overloaded ordinary methods:<br></p>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c04:Overloading.java</font>
<font color=#009900>// Demonstration of both constructor</font>
<font color=#009900>// and ordinary method overloading.</font>
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;
<font color=#0000ff>import</font> java.util.*;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -