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

📄 chapter04.html

📁 java 是一个很好的网络开发环境。由于它是通过解释的方法
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!--
This document was converted from RTF source: 
By rtftohtml 4.19
See http://www.sunpack.com/RTF
Filename:Tjava14.rtf
Application Directory:c:\TOOLS\RTF2HTML\
Subject:
Author:Bruce Eckel
Operator:Bruce Eckel
Document Comments:
Version Comments:
Comments:
Keywords:
Translation Date:02/04/2000
Translation Time:23:24:45
Translation Platform:Win32
Number of Output files:27
This File:Chapter04.html
SplitDepth=1
SkipNavPanel=1
SkipLeadingToc=1
SkipTrailingToc=1
GenContents=1
GenFrames=1
GenIndex=1
-->
<HEAD lang="en"><META http-equiv="Content-Type" content="text/html">
<TITLE>4: Initialization  and cleanup</TITLE>
</HEAD>

<BODY  BGCOLOR="#FFFFFF"><DIV ALIGN="CENTER">
  <a href="http://www.MindView.net">
  <img src="mindview-head.gif" alt="MindView Inc." BORDER = "0"></a>
  <CENTER>
    <FONT FACE="Verdana" size = "-1">
    [ <a href="README-HTML.txt">Viewing Hints</a> ]
    [ <a href="http://www.mindview.net/TIJ2/index.html">2nd Edition</a> ]
    [ <a href="http://www.mindview.net/MailingList.html">Free Newsletter</a> ] <br>
    [ <a href="http://www.mindview.net/Training.html">Seminars</a> ]
    [ <a href="http://www.mindview.net/javaCD2.html">Seminars on CD ROM</a> ]
    [ <a href="http://www.mindview.net/CPPServices/#ConsultingServices">Consulting</a> ]
    </FONT>
  <H2><FONT FACE="Verdana">
  Thinking in Java, 1st edition</FONT></H2>
  <H3><FONT FACE="Verdana">&copy;1998 by Bruce Eckel</FONT></H3>
  
    <FONT FACE="Verdana" size = "-1">
     [ <a href="Chapter03.html">Previous Chapter</a> ] 
    [ <a href="SimpleContents.html">Short TOC</a> ] 
    [ <a href="Contents.html">Table of Contents</a> ] 
    [ <a href="DocIndex.html">Index</a> ]
     [ <a href="Chapter05.html">Next Chapter</a> ] 
    </FONT>
    
  </CENTER>
  </P></DIV><A NAME="Chapter_4"></A><A NAME="_Toc375545274"></A><A NAME="_Toc407441448"></A><A NAME="_Toc408018475"></A><A NAME="Heading136"></A><FONT FACE = "Verdana"><H1 ALIGN="LEFT">
4: Initialization <BR>and cleanup</H1></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Verdana" SIZE=4>As the computer
revolution progresses, &#8220;unsafe&#8221; programming has become one of the
major culprits that makes programming expensive.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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&#8217;t know how to initialize a library component, or even that they
must. Cleanup is a special problem because it&#8217;s easy to forget about an
element when you&#8217;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><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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&#8217;re no
longer being used. This chapter examines the issues of initialization and
cleanup and their support in
Java.</FONT><A NAME="_Toc312373853"></A><A NAME="_Toc375545275"></A><A NAME="_Toc408018476"></A><BR></P></DIV>
<A NAME="Heading137"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
Guaranteed initialization <BR>with the constructor</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">You can imagine creating a method
called <B>initialize(&#160;)</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<A NAME="Index262"></A><A NAME="Index263"></A></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><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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&#8217;s also used in Java: The name of the constructor
<A NAME="Index264"></A>is the same as the name of the class. It makes sense that
such a method will be called automatically on initialization.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Here&#8217;s a simple class with a
constructor: </FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: SimpleConstructor.java</font>
<font color=#009900>// Demonstration of a simple constructor</font>
<font color=#0000ff>package</font> c04;

<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>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 &lt; 10; i++)
      <font color=#0000ff>new</font> Rock();
  }
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Now, when an
<A NAME="Index265"></A>object is created:</FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#0000ff>new</font> Rock();</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Note that the coding style of
making the first letter of all methods lower case does not apply to
constructors, since the name of the constructor must match the name of the class
<I>exactly</I>.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Like any method, the constructor
can have arguments<A NAME="Index266"></A><A NAME="Index267"></A> to allow you to
specify <I>how</I> an object is created. The above example can easily be changed
so the constructor takes an argument:</FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#0000ff>class</font> Rock {
  Rock(<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> SimpleConstructor {
  <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 &lt; 10; i++)
      <font color=#0000ff>new</font> Rock(i);
  }
}</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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><BR></P></DIV>
<DIV ALIGN="LEFT"><P><TT><FONT FACE="Courier New">Tree t = new Tree(12);  //
12-foot tree</FONT></TT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">If <B>Tree(int)</B> is your only
constructor, then the compiler won&#8217;t let you create a <B>Tree</B> object
any other way. </FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Constructors eliminate a large
class of problems and make the code easier to read. In the preceding code
fragment, for example, you don&#8217;t see an explicit call to some
<B>initialize(&#160;)</B> method that is conceptually separate from definition.
In Java, definition and initialization are unified concepts &#8211; you
can&#8217;t have one without the other.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The constructor is an unusual type
of method because it has no return
value<A NAME="Index268"></A><A NAME="Index269"></A>. This is distinctly
different from 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&#8217;t have an option. 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><A NAME="_Toc375545276"></A><A NAME="_Toc408018477"></A><BR></P></DIV>
<A NAME="Heading138"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
Method overloading<BR><A NAME="Index270"></A><A NAME="Index271"></A></H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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&#8217;s a lot like writing prose &#8211; the goal is
to communicate with your readers.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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 &#8211; it&#8217;s
<I>overloaded</I>. This is useful, especially when it comes to trivial
differences. You say &#8220;wash the shirt,&#8221; &#8220;wash the car,&#8221;
and &#8220;wash the dog.&#8221; It would be silly to be forced to say,
&#8220;shirtWash the shirt,&#8221; &#8220;carWash the car,&#8221; and
&#8220;dogWash the dog&#8221; just so the listener doesn&#8217;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&#8217;t need unique identifiers &#8211; we can deduce meaning from
context.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">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(&#160;)</B> for printing integers
and another called <B>print(&#160;)</B> for printing floats &#8211; each
function requires a unique name.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">In Java, another factor forces the
overloading of method names: the
constructor<A NAME="Index272"></A><A NAME="Index273"></A>. Because the
constructor&#8217;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 and by reading information from a file. You need two constructors,
one that takes no arguments (the <I>default</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
&#8211; 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&#8217;s a general
convenience and can be used with any method. </FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Here&#8217;s an example that shows

⌨️ 快捷键说明

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