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

📄 ch2.htm

📁 JAVA Developing Professional JavaApplets
💻 HTM
📖 第 1 页 / 共 5 页
字号:
data type and return a String representation. The following codesets the String variable <TT>s</TT>to <TT>100</TT>.<BLOCKQUOTE><TT>int i = 100;<BR>String s = String.valueOf(i);</TT></BLOCKQUOTE><P>Notice that the preceding example didn't use any instance of theString class to invoke the <TT>valueOf()</TT>method. This is because <TT>valueOf()</TT>is a <I>class</I> <I>method</I>, which means that the method isglobal to the class, not to a specific instance of the class.Class methods (sometimes called <I>static methods</I>) are discussedin the section &quot;Class Methods and Class Variables&quot; later,but keep this syntax in mind when you see it.<P>The <TT>equals()</TT> method returnsa boolean indicating whether two String objects have identicalinternal strings. The call<BLOCKQUOTE><TT>s2.equals(s);</TT></BLOCKQUOTE><P>using the String variables from the previous example returns <TT>false</TT>.The String class has many methods; you'll see many of these usedin the examples and chapter projects of this book.<P>Another type of string class is StringBuffer. Unlike the Stringclass, you can modify a StringBuffer object after you've createdit. You typically construct a StringBuffer object with a Stringas the lone parameter, although other variations are possible.After construction, you can use operations like <TT>append()</TT>to modify its state. Using the two String variables again in anexample, the following code creates the same String value as variable<TT>s2</TT>, except with a periodconcatenated to the end:<BLOCKQUOTE><TT>StringBuffer sb = new StringBuffer(s2);<BR>sb.append('.');<BR>System.out.println(sb);</TT></BLOCKQUOTE><P>The StringBuffer class has some of the same methods as String,and you usually use it in close conjunction with String objects.<H3><A NAME="TypeWrappers">Type Wrappers</A></H3><P>As pointed out in <A HREF="ch1.htm" >Chapter 1</A>, &quot;TheJava Development Environment,&quot; Java had some important designdecisions to make regarding primitive data types like integersand floating point numbers. On one hand, designers of Java wantedit to be &quot;objects all the way down,&quot; while on the otherhand, it needed good performance. In other object-oriented languages,such as Smalltalk, everything is an object, including a number.To perform a mathematical operation would then actually be anapplication of a method. However, this purity comes at the expenseof performance; methods calls are relatively expensive comparedto, say, an addition of two integers.<P>Java uses a middle-ground approach. You can work with the primitivedata types directly so that<BLOCKQUOTE><TT>int x = 2 + x2;</TT></BLOCKQUOTE><P>does not result in an object method call. However, if you wantto use numbers or other data types of objects, you can use instancesof a special set of classes called <I>type wrappers</I>. Eachof the primitive data types has a type wrapper class, as shownin Table 2.1.<BR><P><CENTER><B>Table 2.1. Type wrapper classes.</B></CENTER><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=124><I>Class</I></TD><TD WIDTH=376><I>Description</I></TD></TR><TR VALIGN=TOP><TD WIDTH=124><TT>Boolean</TT></TD><TD WIDTH=376>Object wrapper for the <TT>boolean</TT> data type</TD></TR><TR VALIGN=TOP><TD WIDTH=124><TT>Character</TT></TD><TD WIDTH=376>Object wrapper for the <TT>char</TT> data type</TD></TR><TR VALIGN=TOP><TD WIDTH=124><TT>Double</TT></TD><TD WIDTH=376>Object wrapper for <TT>double</TT> data type</TD></TR><TR VALIGN=TOP><TD WIDTH=124><TT>Float</TT></TD><TD WIDTH=376>Wrapper for <TT>float</TT> data type</TD></TR><TR VALIGN=TOP><TD WIDTH=124><TT>Integer</TT></TD><TD WIDTH=376>Wraps <TT>integer</TT> data type</TD></TR><TR VALIGN=TOP><TD WIDTH=124><TT>Long</TT></TD><TD WIDTH=376>Type wrapper for <TT>long</TT> data type</TD></TR><TR VALIGN=TOP><TD WIDTH=124><TT>Number</TT></TD><TD WIDTH=376>A superclass that defines methods of numeric type wrappers</TD></TR></TABLE></CENTER><P><P>You can create wrappers in a variety of ways depending on thedata type. You can create instances of the Integer class in twoways:<BLOCKQUOTE><TT>Integer I1 = new Integer(6);<BR>Integer I2 = new Integer(&quot;6&quot;);</TT></BLOCKQUOTE><P>Once created, you can apply a suite of methods. You can use someof these to convert the internal value to a new data type. Forexample, the preceding code returns a double value for the integer<TT>6</TT>:<BLOCKQUOTE><TT>double dbl = I1.doubleValue();</TT></BLOCKQUOTE><P>As with the String class, you can employ class methods to performoperations on primitive data types without creating an instanceof a class. For example, the following code converts a stringto an integer:<BLOCKQUOTE><TT>int i = Integer.parseInt(&quot;6&quot;);</TT></BLOCKQUOTE><P>If the String cannot be converted to a number, a NumberFormatExceptionobject is thrown. Exceptions are discussed later in the section&quot;Introduction to Exception Handling.&quot;<P>Finally, the type wrappers provide public variables that giveinformation about such things as the upper and lower bounds ofa data type. To get the maximum value a <TT>double</TT>primitive type can have, you may call the following:<BLOCKQUOTE><TT>System.out.println(&quot;Max double value:&quot; + Double.MAX_VALUE);</TT></BLOCKQUOTE><P>The <TT>MAX_VALUE</TT> public variableis a class variable of the Double class and is declared as staticas in class methods. You learn more about these types of variablesin the section &quot;Class Methods and Class Variables.&quot;<BR><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>Note</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Now that you have seen some of Java's core classes, you can gain some further insight into Java arrays; as stated earlier, arrays are first-class objects. Because Object is the base class, this implies that arrays are subclasses of the Object class. Actually there is a class called Array, which is a direct subclass of Object. For each primitive type and class, there is a subclass of Array. Thus, there is a String[] and int[] class. Inheritance relationships are also maintained in this Array hierarchy. Turning back to the first inheritance example, the AddressRecord[] class is a subclass of SimpleRecord[].</BLOCKQUOTE><BLOCKQUOTE>Because arrays are subclasses of Object, this means that you can apply Object methods to it. For example, this is legal:</BLOCKQUOTE><BLOCKQUOTE><TT>String s[] = new String[4];<BR>System.out.println(&quot;S Superclass: &quot; + s.getClass().getSuperclass());</TT></BLOCKQUOTE><BLOCKQUOTE>Therefore, you can assign arrays to Objects. These are all valid calls:</BLOCKQUOTE><BLOCKQUOTE><TT>String s[] = new String[4];<BR>Object oArray[] = s;<BR>int numbers[] = new int[4];<BR>System.out.println(numbers);<BR>Object o = numbers;</TT></BLOCKQUOTE><BLOCKQUOTE>However, you cannot explicitly subclass an array.</BLOCKQUOTE></TD></TR></TABLE></CENTER><H2><A NAME="MoreaboutClasses"><FONT SIZE=5 COLOR=#FF0000>Moreabout Classes</FONT></A></H2><P>It is time to go back to the mechanics of using Java classes.However, with the basics and a description of some core classesbehind you, you're ready for some more advanced class constructs.<H3><A NAME="AccessModifiers">Access Modifiers</A></H3><P>Java uses access control modifiers to specify the level of visibilitya method or variable has to other classes. Java has four levelsof access: <TT>public</TT>, <TT>private</TT>,<TT>protected</TT>, and <TT>package</TT>.The first three are straightforward and may be familiar; the <TT>package</TT>access level is a little more involved.<P>The <TT>public</TT> modifier indicatesthat you can access a variable by any class or method. Constructorsare usually <TT>public</TT>, as inthe AddressRecord example from earlier:<BLOCKQUOTE><TT>class AddressRecord extends SimpleRecord{<BR>&nbsp;&nbsp;&nbsp;// Default constructor<BR>&nbsp;&nbsp;&nbsp;public AddressRecord() {<BR>&nbsp;&nbsp;&nbsp;&nbsp; //...<BR>&nbsp;&nbsp;&nbsp;}<BR>}</TT></BLOCKQUOTE><P>You can also declare a variable as <TT>public</TT>.For example, you can extend the AddressRecord class to have two<TT>public</TT>/FONT></TT> variables to indicatewhether the address is for the Internet or is physical:<BLOCKQUOTE><TT>class AddressRecord extends SimpleRecord{<BR>&nbsp;&nbsp;&nbsp;public int INTERNET_ADDRESS = 0;<BR>&nbsp;&nbsp;&nbsp;public int PHYSICAL_ADDRESS = 1;<BR>&nbsp;&nbsp;&nbsp;// ... Constructors and methods...<BR>&nbsp;&nbsp;&nbsp;}<BR>}</TT></BLOCKQUOTE><P>You can use the following code to print its values:<BLOCKQUOTE><TT>AddressRecord a = new AddressRecord();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(&quot;PhysicalAddress = &quot; +<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;a.PHYSICAL_ADDRESS);&nbsp;&nbsp;//which is 1</TT></BLOCKQUOTE><P>You use the <TT>protected</TT> accessorto restrict access only to subclasses of the protected class.This accessor allows you to design classes so that you can specifymethods only of use to subclasses. For example, you can make thename variables of SimpleRecord <TT>protected</TT>.This restricts their use to a subclass, such as AddressRecord.This is how the variable portion of SimpleRecord is defined:<BLOCKQUOTE><TT>class SimpleRecord {<BR>&nbsp;&nbsp;&nbsp;protected String firstName;<BR>&nbsp;&nbsp;&nbsp;protected String lastName;<BR>&nbsp;&nbsp;&nbsp;// ... Constructors and methods...<BR>}</TT></BLOCKQUOTE><P>The AddressRecord class can continue to use these variables, butoutside classes cannot access them.<P>The <TT>private</TT> accessor indicatesthat a variable or method is not available to any other classexcept the one in which it appears. For example, recall that the<TT>list()</TT> method of SimpleRecordis called by the AddressRecord subclass. This can happen becauseaccess to the method is allowed. However, if the method is declaredas <TT>private</TT>,<BLOCKQUOTE><TT>private void list()</TT></BLOCKQUOTE><P>then AddressRecord will not be able to access the method. A compilationerror will therefore arise when you try to compile the AddressRecordclass.<P>The last and default form of access, <TT>package</TT>,does not directly correspond to an accessor keyword. <I>Packages</I>,as discussed in the section of the same name, are a way of creatinglibraries of classes. If you do not specify an access controlmodifier, a method or variable is accessible to all classes inthe <TT>package</TT>. The <TT>package</TT>level of access is a way of saying that the method or variableis accessible to all classes that are &quot;friends&quot; with,or the same <TT>package</TT> as, theclass they're contained in.<H3><A NAME="ClassMethodsandClassVariables">Class Methods andClass Variables</A></H3><P>Sometimes you may need to have information that is global to aclass and shared by every instance of that class. One reason youmight want to do this is for values that do not change, as indefining mathematical constants, like pi. Or you may want to definea version number for a class. Finally, if your class is providinga service that is used throughout an applet, you may want to makeits data global to the class so that objects can share the information.<P><I>Class</I><B> </B><I>methods</I> and <I>class</I><B> </B><I>variables</I>are employed to define data that is local to a class and not anobject. For this reason, class variables are different from instancevariables. Class methods and class variables are declared by usingthe <TT>static</TT> keyword, whichsometimes results in them being referred to as <I>static</I><B></B><I>methods</I> and <I>static</I><B> </B><I>variables</I>.<P>From the ever present AddressRecord example, you can make thetwo public address flags into class variables by adding the <TT>static</TT>keyword:<BLOCKQUOTE><TT>class AddressRecord extends SimpleRecord{<BR>&nbsp;&nbsp;&nbsp;public static int INTERNET_ADDRESS = 0;<BR>&nbsp;&nbsp;&nbsp;public static int PHYSICAL_ADDRESS = 1;<BR>&nbsp;&nbsp;&nbsp;// ... Constructors and methods...<BR>&nbsp;&nbsp;&nbsp;}<BR>}</TT></BLOCKQUOTE><P>This is more efficient than the previous use that just declaredthe addresses as <TT>public</TT>.By adding the <TT>static</TT> keyword,you have indicated that these flags are global to the class andnot the particular instance.<P>Class methods are even more interesting. In Part III of this book,you will create a class that keeps track of images that have beenloaded in memory. This class information is kept across invocationsof applets, so some of this class information doesn't need tobe tied to a particular instance. In fact, there is only one instanceof the class, and it is invoked by the class itself! The classdoes this through a private constructor. Here are some of thecode highlights:<BLOCKQUOTE><TT>public class MediaLoader {<BR>&nbsp;&nbsp;&nbsp;// Cache is hashtable...<BR><BR>

⌨️ 快捷键说明

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