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

📄 ch4.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 2 页
字号:
called a car. Moreover, all these functions work very similarlyfrom one car to the next. You're not likely to confuse a car witha dishwasher, a tree, or a playground. A car is a complete unit-anobject with unique properties.<P>You can also think of a computer program as consisting of objects.Instead of thinking of a piece of code that, for example, drawsa rectangle on-screen, and another piece of code that fills therectangle with text, and still another piece of code that enablesyou to move the rectangle around the screen, you can think ofa single object: a window. This window object contains all thecode that it needs in order to operate. Moreover, it also containsall the data that it needs. This is the philosophy behind OOP.<H2><A NAME="ObjectOrientedProgramming"><FONT SIZE=5 COLOR=#Ff0000>Object-Oriented Programming</FONT></A></H2><P>Object-oriented programming enables you to think of program elementsas objects. In the case of a window object, you don't need toknow the details of how it works, nor do you need to know aboutthe window's private data fields. You need to know only how tocall the various functions (called methods in Java) that makethe window operate. Consider the car object discussed in the previoussection. To drive a car, you don't have to know the details ofhow a car works. You need to know only how to drive it. What'sgoing on under the hood is none of your business. (And, if youcasually try to make it your business, plan to face an amusedmechanic who will have to straighten out your mess!)<P>But OOP is a lot more than just a way to hide the details of aprogram. To learn about OOP, you need to understand three mainconcepts that are the backbone of OOP. These concepts, which arecovered in the following sections, are: encapsulation, inheritance,and polymorphism.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>If you're new to programming, you might want to stop reading at this point and come back to this chapter after you've studied Chapters 5 through 14. It's not possible to discuss concepts such as encapsulation, inheritance, and polymorphism without dealing with such subjects as data types, variables, and variable scope. If these terms are unfamiliar, move on now to <A HREF="ch5.htm" >Chapter 5</A></BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="Encapsulation">Encapsulation</A></H3><P>One major difference between conventional structured programmingand object-oriented programming is a handy thing called encapsulation.Encapsulation enables you to hide, inside the object, both thedata fields and the methods that act on that data. (In fact, datafields and methods are the two main elements of an object in theJava programming language.) After you do this, you can controlaccess to the data, forcing programs to retrieve or modify dataonly through the object's interface. In strict object-orienteddesign, an object's data is always private to the object. Otherparts of a program should never have direct access to that data.<P>How does this data-hiding differ from a structured-programmingapproach? After all, you can always hide data inside functions,just by making that data local to the function. A problem arises,however, when you want to make the data of one function availableto other functions. The way to do this in a structured programis to make the data global to the program, which gives any functionaccess to it. It seems that you could use another level of scope-onethat would make your data global to the functions that need it-butstill prevent other functions from gaining access. Encapsulationdoes just that. In an object, the encapsulated data members areglobal to the object's methods, yet they are local to the object.They are not global variables.<H3><A NAME="ClassesasDataTypes">Classes as Data Types</A></H3><P>An object is just an instance of a data type. For example, whenyou declare a variable of type <TT>int</TT>, you're creating aninstance of the <TT>int</TT> data type. A class is like a datatype in that it is the blueprint upon which an object is based.When you need a new object in a program, you create a class, whichis a kind of template for the object. Then, in your program, youcreate an instance of the class. This instance is called an object.<P>Classes are really nothing more than user-defined data types.As with any data type, you can have as many instances of the classas you want. For example, you can have more than one window ina Windows application, each with its own contents.<P>For example, think again about the integer data type (<TT>int)</TT>.It's absurd to think that a program can have only one integer.You can declare many integers, just about all you want. The sameis true of classes. After you define a new class, you can createmany instances of the class. Each instance (called an object)normally has full access to the class's methods and gets its owncopy of the data members.<H3><A NAME="Inheritance">Inheritance</A></H3><P>Inheritance enables you to create a class that is similar to apreviously defined class, but one that still has some of its ownproperties. Consider a car-simulation program. Suppose that youhave a class for a regular car, but now you want to create a carthat has a high-speed passing gear. In a traditional program,you might have to modify the existing code extensively and mightintroduce bugs into code that worked fine before your changes.To avoid these hassles, you use the object-oriented approach:Create a new class by inheritance. This new class inherits allthe data and methods from the tested base class. (You can controlthe level of inheritance with the <TT>public</TT>, <TT>private</TT>,and <TT>protected</TT> keywords. You'll see how all this workswith Java in <A HREF="ch14.htm" >Chapter 14</A>, &quot;Classes.&quot;) Now, you only needto worry about testing the new code you added to the derived class.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>The designers of OOP languages didn't pick the word &quot;inheritance&quot; out of a hat. Think of how human children inherit many of their characteristics from their parents. But the children also have characteristics that are uniquely their own. In object-oriented programming, you can think of a base class as a parent and a derived class as a child.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="Polymorphism">Polymorphism</A></H3><P>The last major feature of object-oriented programming is polymorphism.By using polymorphism, you can create new objects that performthe same functions as the base object but which perform one ormore of these functions in a different way. For example, you mayhave a shape object that draws a circle on the screen. By usingpolymorphism, you can create a shape object that draws a rectangleinstead. You do this by creating a new version of the method thatdraws the shape on the screen. Both the old circle-drawing andthe new rectangle-drawing method have the same name (such as <TT>DrawShape()</TT>)but accomplish the drawing in a different way.<H3><A NAME="ExampleEncapsulationInheritanceandPolymorphism">Example: Encapsulation, Inheritance, and Polymorphism</A></H3><P>Although you won't actually start using Java classes until laterin this book, this is a good time to look at OOP concepts in ageneral way. As an example, you'll extend the car metaphor youread earlier this chapter.<P>In that section I described a car as an object having severalcharacteristics (direction, position, and speed) and several means(steering wheel, gas pedal, and brakes) to act on those characteristics.In terms of constructing a class for a car object, you can thinkof direction, position, and speed as the class's data fields andthe steering wheel, gas pedal, and brakes as representing theclass's methods.<P>The first step in creating an object is to define its class. Fornow, you'll use pseudo-code to create a <TT>Car</TT> class. You'lllearn about Java classes in <A HREF="ch14.htm" >Chapter 14</A>, &quot;Classes.&quot; Thebase <TT>Car</TT> class might look like Listing 4.1.<HR><BLOCKQUOTE><B>Listing 4.1&nbsp;&nbsp;LST4_1.TXT: The pseudocode for a BaseCar Class.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>class Car{    data direction;    data position;    data speed;    method Steer();    method PressGasPedal();    method PressBrake();}</PRE></BLOCKQUOTE><HR><P>In this base <TT>Car</TT> class, a car is defined by its direction(which way its pointed), position (where it's located), and speed.These three data fields can be manipulated by the three methods<TT>Steer()</TT>, <TT>PressGasPedal()</TT>, and <TT>PressBrake()</TT>.The <TT>Steer()</TT> method changes the car's direction, whereasthe <TT>PressGasPedal()</TT> and <TT>PressBrake()</TT> changethe car's speed. The car's position is affected by all three methods,as well as by the direction and speed settings.<P>The data fields and methods are all encapsulated inside the class.Moreover, the data fields are private to the class, meaning thatthey cannot be directly accessed from outside of the class. Onlythe class's three methods can access the data fields. In short,Listing 4.1 not only shows what a class might look like, it alsoshows how encapsulation works.<P>Now, suppose you want to create a new car that has a special passinggear. To do this, you can use OOP inheritance to derive a newclass from the <TT>Car</TT> base class. Listing 4.2 is the pseudocodefor this new class.<HR><BLOCKQUOTE><B>Listing 4.2&nbsp;&nbsp;LST4_1.TXT: Deriving a New Class UsingInheritance.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>Class PassingCar inherits from Car{    method Pass();}</PRE></BLOCKQUOTE><HR><P>You may be surprised to see how small this new class is. It'ssmall because it implicitly inherits all the data fields and methodsfrom the <TT>Car</TT> base class. That is, not only does the <TT>PassingCar</TT>class have a method called <TT>Pass()</TT>, but it also has the<TT>direction</TT>, <TT>position</TT>, and <TT>speed</TT> datafields, as well as the <TT>Steer()</TT>, <TT>PressGasPedal()</TT>,and <TT>PressBrake()</TT> methods. The <TT>PassingCar</TT> classcan use all these data fields and methods exactly as if they wereexplicitly defined in Listing 4.2. This is an example of inheritance.<P>The last OOP concept that you'll apply to the car classes is polymorphism.Suppose that you now decide that you want a new kind of car thathas all the characteristics of a <TT>PassingCar</TT>, except thatits passing gear is twice as fast as <TT>PassingCar</TT>'s. Youcan solve this problem as shown in Listing 4.3.<HR><BLOCKQUOTE><B>Listing 4.3&nbsp;&nbsp;LST4_3.TXT: Using Polymorphism to Createa Faster Car.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>class FastCar inherits from PassingCar{    method Pass();}</PRE></BLOCKQUOTE><HR><P>The <TT>FastCar</TT> class looks exactly like the original <TT>PassingCar</TT>class. However, rather than just inheriting the <TT>Pass()</TT>method, it defines its own version. This new version makes thecar move twice as fast as <TT>PassingCar</TT>'s <TT>Pass()</TT>method does (the code that actually implements each method isnot shown). In this way, the <TT>FastCar</TT> class implementsthe same functionality as the <TT>PassingCar()</TT> class, butit implements that functionality a little differently.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Because the <TT>FastCar</TT> class inherits from <TT>PassingCar</TT>, which itself inherits from <TT>Car</TT>, a <TT>FastCar</TT> also inherits all the data fields and methods of the <TT>Car</TT> class. There are ways that you can control how inheritance works (using the <TT>public</TT>, <TT>protected</TT>, and <TT>private</TT> keywords), but you won't get into that until much later in this book.</BLOCKQUOTE></TD></TR></TABLE></CENTER><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>,  All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>

⌨️ 快捷键说明

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