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

📄 ch2.htm

📁 JAVA Developing Professional JavaApplets
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return half;<BR>}</TT></BLOCKQUOTE><P>The variable <TT>half</TT> is a localvariable; it will not exist after the <TT>getHalf()</TT>method is finished. However, the <TT>firstVariable</TT>instance variable hangs around until the object instance is destroyed.<P>Note that the <TT>getHalf()</TT> localvariable isn't really needed. This method could have gotten thesame results in a single <TT>return</TT>statement:<BLOCKQUOTE><TT>public int getHalf() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return firstVariable / 2;<BR>}</TT></BLOCKQUOTE><H3><A NAME="CreatinganObjectInstance">Creating an Object Instance</A></H3><P>After defining a class, you can use it as a runtime object. Usethe <TT>new</TT> operator to createan instance of a class. You can use the following code to createan object instance of the FirstClass class:<BLOCKQUOTE><TT>FirstClass firstObject = new FirstClass();</TT></BLOCKQUOTE><P>The <TT>new</TT> operator does a coupleof things. First, it allocates memory for the object. Recall thatJava has automatic memory management; consequently, you don'thave to explicitly allocate memory. The <TT>new</TT>operator also initializes instance variables. In this sample class,<TT>firstVariable</TT> is set to aninitial value of zero. However, the explicit initialization tozero is not necessary; Java automatically sets instance variablesto initial values such as zero or null.<P>The <TT>new</TT> operator also callsa <I>constructor</I><B>.</B> A constructor is a method calledwhen an object is instantiated. You can use a constructor to provideadditional initialization. Constructors are discussed in greaterdetail in the &quot;Constructors&quot; section of this chapter.<H3><A NAME="UsingMethods">Using Methods</A></H3><P>A <I>method</I> has two parts: a <I>definition</I> and a <I>body</I>.The definition must have at least three components: a <I>returnvalue</I>, a <I>name</I>, and a <I>parameter list</I>. These threecomponents define the <I>signature</I> of a method. As you willsee in the next section, signatures are important because youcan use a method name multiple times in a class.<P>The return value of a method can be a primitive data type (suchas <TT>int</TT>), a class name (suchas String), or <TT>void</TT> if thereis no return value. A method has zero or more parameters. If thereare no parameters, the method consists of empty parentheses; otherwise,the parameters can be primitive data types or classes, separatedby commas.<P>It's easy to call object methods. The following code instantiatesa FirstClass object and manipulates its internal variable values:<BLOCKQUOTE><TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;FirstClassfirstObject;&nbsp;&nbsp;// Object not <BR>instantiated yet<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;firstObject = new FirstClass();// Object <BR>instantiated!<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// See what the default valueof the object is...<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int val = firstObject.getValue();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Valueof firstObject = &quot; + <BR>val);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Set it to a new value...<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;firstObject.setValue(1000);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Valueof firstObject = &quot; +<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;firstObject.getValue());<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;HalfValue of firstObject = &quot; <BR>+<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;firstObject.getHalf());</TT></BLOCKQUOTE><P>Recall that <TT>System.out.println</TT>prints a string to standard output. In this example, the first<TT>Print</TT> statement outputs avalue of <TT>0</TT>, which was theinitialized value of <TT>firstVariable</TT>.The code then sets that variable to a value of <TT>1000</TT>by using the <TT>setValue()</TT> method.When its value prints again, a value of <TT>1000</TT>is output. Finally, the code calls the <TT>getHalf()</TT>method to print half the instance variable's value, namely <TT>500</TT>.<H3><A NAME="OverloadingMethods">Overloading Methods</A></H3><P>As mentioned earlier, a method has a signature. This is importantbecause Java provides a mechanism for repeatedly using the samemethod name; this mechanism is called <I>overloading</I>. An overloadedmethod has the same name but different parameters. To illustrateoverloading, a class is created that defines two instance variables.This class, called SecondClass, illustrates overloading by providingtwo methods of the same name to set the instance variables:<BLOCKQUOTE><TT>class SecondClass {<BR>&nbsp;&nbsp;&nbsp;int var1 = 1;<BR>&nbsp;&nbsp;&nbsp;int var2 = 2;<BR>&nbsp;&nbsp;&nbsp;// Set only the first variable<BR>&nbsp;&nbsp;&nbsp;public void setVar(int newVal1) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var1 = newVal1;<BR>&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;&nbsp;// Overloaded! Set both variables...<BR>&nbsp;&nbsp;&nbsp;public void setVar(int newVal1,int newVal2){<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var1 = newVal1;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var2 = newVal2;<BR>&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;&nbsp;// Get variable values...<BR>&nbsp;&nbsp;&nbsp;public int getVar1() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return var1;<BR>&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;&nbsp;public int getVar2() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return var2;<BR>&nbsp;&nbsp;&nbsp;}<BR>}</TT></BLOCKQUOTE><P>The version of <TT>setVar()</TT> withone parameter sets the value of variable <TT>1</TT>;the <TT>setVar()</TT> version withtwo parameters sets both variable values. The following code showshow you can use this class:<BLOCKQUOTE><TT>SecondClass secondObject = new SecondClass();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Var1=&quot;+ <BR>secondObject.getVar1()<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ &quot;Var2= &quot; + secondObject.getVar2());<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;secondObject.setVar(1000);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Var1=&quot;+ <BR>secondObject.getVar1()<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ &quot;Var2= &quot; + secondObject.getVar2());<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;secondObject.setVar(secondObject.getVar1()/2,<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;secondObject.getVar1());<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;Var1=&quot;+ <BR>secondObject.getVar1()<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ &quot;Var2= &quot; + secondObject.getVar2());</TT></BLOCKQUOTE><P>After you call the first <TT>print</TT>method, the output is <TT>1</TT> and<TT>2</TT>, the initialized valuesof the two variables. The code then uses the first version of<TT>setVar()</TT> to set the firstvariable to a value of <TT>1000</TT>.The second <TT>print</TT> call printsthe values <TT>1000</TT> and <TT>2</TT>.Finally, the other <TT>setVar()</TT>method is called to set both variables. The first variable isset to half its existing value, and the second variable is setto half the existing value. Parameters resolve fully before passingto the called method. This means that half of the existing firstvariable value of <TT>500</TT> passesto the first parameter, but the full value of <TT>1000</TT>passes to the second parameter. The consequent printing displays<TT>500</TT> and <TT>1000</TT>for SecondClass object variables <TT>var1</TT>and <TT>var2</TT>, respectively.<P>Periodically, you might hear method invocation called &quot;messagepassing&quot; or &quot;sending a message.&quot; This is object-oriented&quot;lingo&quot; for talking about how two objects communicate.The reason that message passing is more than a buzzword is becauseof what goes on behind the scenes when a method is invoked. Becausea method can be overloaded (and overridden, as you'll see in thesection on &quot;Method Overriding&quot;), an invocation of anobject actually results in the receiving object performing a lookupto see which method should be called. Consequently, it is morecorrect to call the procedure a &quot;message passing&quot; becausethe method invocation is not a direct call (such as calling afunction in C) but a request for action.<H3><A NAME="Constructors">Constructors</A></H3><P>As stated earlier, <I>constructors</I> are a special type of methodcalled when an object is initialized; their syntax is similarto that of methods, except they don't return values. The nameof a constructor is the same as its class. A constructor is automaticallycalled when an object is instantiated.<P>Now, rework the SecondClass class to illustrate constructors.First, add a default constructor:<BLOCKQUOTE><TT>class SecondClass {<BR>&nbsp;&nbsp;&nbsp;int var1;<BR>&nbsp;&nbsp;&nbsp;int var2;<BR>&nbsp;&nbsp;&nbsp;// Main constructor...<BR>&nbsp;&nbsp;&nbsp;public SecondClass() {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var1 = 1;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var2 = 2;<BR>&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;&nbsp;// ... OTHER METHODS GO HERE...<BR>}</TT></BLOCKQUOTE><P>Rather than setting the values of the instance variables in theirdeclaration, set them in the constructor. This constructor iscalled if you create an instance of SecondClass, as follows:<BLOCKQUOTE><TT>SecondClass secondObject = new SecondClass();</TT></BLOCKQUOTE><P>As with methods, you can overload constructors. Here is a constructorthat defines the variable <TT>var1</TT>at creation:<BLOCKQUOTE><TT>// Another constructor...<BR>&nbsp;&nbsp;&nbsp;public SecondClass(int var1) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.var1 = var1;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var2 = 2;<BR>&nbsp;&nbsp;&nbsp;}</TT></BLOCKQUOTE><P>To instantiate an object with this constructor, use the following:<BLOCKQUOTE><TT>SecondClass secondObject = new SecondClass(100);</TT></BLOCKQUOTE><P>This call creates an object with <TT>var1</TT>set to <TT>100</TT>; <TT>var2</TT>is set to <TT>2</TT>.<P>You may have noticed the curious way <TT>var1</TT>is set in the new constructor.<BLOCKQUOTE><TT>this.var1 = var1;</TT></BLOCKQUOTE><P>In this code, <TT>this</TT> refersto the current instance of the object, so use <TT>this</TT>to differentiate the <TT>var1</TT>of the object from that of the parameter. Because local variablesand parameter variables are first in scope, they will be usedunless the <TT>this</TT> keyword isused. Effectively, <TT>this</TT> appearsin front of every call to an object's variable, so this is the<TT>var2</TT> initialization of theconstructor:<BLOCKQUOTE><TT>this.var2 = 2;</TT></BLOCKQUOTE><P>To round out this example, you can use a third constructor toset both the variable's initial values:<BLOCKQUOTE><TT>// Define both values at initialization<BR>&nbsp;&nbsp;&nbsp;public SecondClass(int var1,int var2) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.var1 = var1;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.var2 = var2;<BR>&nbsp;&nbsp;&nbsp;}</TT></BLOCKQUOTE><P>You can call this constructor with the following:<BLOCKQUOTE><TT>SecondClass secondObject = new SecondClass(100,200);</TT></BLOCKQUOTE><P>This call creates an object with <TT>var1</TT>set to <TT>100</TT>; <TT>var2</TT>is set to <TT>200</TT>.<P>What happens if there is no constructor, as in the earlier examples?In this case, the constructor of the class's <I>superclass</I>is called. This brings up the subject of <I>inheritance</I> inJava.<H2><A NAME="InheritanceinJava"><FONT SIZE=5 COLOR=#FF0000>Inheritancein Java</FONT></A></H2><P>One of the distinguishing features of object-oriented languagesis <I>inheritance, </I>a mechanism you can use to create a newclass by extending the definition of another class. It gives youa powerful way to increase the reusability of your code. You cantake an old class and use it to create a new class by definingthe differences between your new class and the old one. The oldextended class is the <I>superclass</I>; the new extended classis the <I>subclass</I>. In Java, the process of extending oneclass to create a new class is called <I>subclassing</I>.<H3><A NAME="Subclassing">Subclassing</A></H3><P>Java uses the <TT>extends</TT> keywordto indicate the creation of a new class as a subclass of an existingclass. To illustrate subclassing, the following code creates asimple class that keeps a record of people's first and last names.It has a default constructor that simply initializes the two names,a constructor for storing String parameters, and a <TT>list()</TT>

⌨️ 快捷键说明

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