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

📄 ch14.htm

📁 this is a book on pearl , simple example with explanation is given here. it could be beneficial for
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<HTML><HEAD><TITLE>Chapter 14  -- What Are Objects?</TITLE><META></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#0000EE" VLINK="#551A8B" ALINK="#CE2910"><H1><FONT SIZE=6 COLOR=#FF0000>Chapter&nbsp;14</FONT></H1><H1><FONT SIZE=6 COLOR=#FF0000>What Are Objects?</FONT></H1><HR><P><CENTER><B><FONT SIZE=5>CONTENTS</FONT></B></CENTER><UL><LI><A HREF="#LearningaboutClasses">Learning about Classes</A><LI><A HREF="#AbstractThinking">Abstract Thinking</A><LI><A HREF="#OverridingMethodswithPolymorphism">Overriding Methods with Polymorphism</A><LI><A HREF="#KeepingCodeandDataTogetherwithENCapsulation">Keeping Code and Data Together with ENCapsulation</A><LI><A HREF="#HowPerlHandlesObjects">How Perl Handles Objects</A><UL><LI><A HREF="#ExampleBlesstheHashandPasstheRefereNCe">Example: Bless the Hash and Pass the RefereNCe</A><LI><A HREF="#ExampleInitializingProperties">Example: Initializing Properties</A><LI><A HREF="#ExampleUsingNamedParametersinConstructors">Example: Using Named Parameters in Constructors</A><LI><A HREF="#ExampleInheritaNCePerlStyle">Example: InheritaNCe, Perl Style</A><LI><A HREF="#ExamplePolymorphism">Example: Polymorphism</A><LI><A HREF="#ExampleHowOneClassCanContainAnother">Example: How One Class Can Contain Another</A></UL><LI><A HREF="#StaticVersusRegularMethodsandVariables">Static Versus Regular Methods and Variables</A><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>Actually, &quot;What are objects?&quot; is a silly question becauseyou already know what an object is. Trust your instiNCts. Thebook you are reading is an object. The knife and fork you eatwith are objects. In short, your life is filled with them.<P>The question that really needs to be asked is, &quot;What areclasses?&quot; You see, all object-oriented techniques use classesto do the real work. A <I>class</I> is a combination of variablesand fuNCtions designed to emulate an object. However, when referringto variables in a class, object-oriented folks use the term <I>properties</I>;and when referring to fuNCtions in a class, the term <I>method</I>is used.<P>I'm not sure why new terminology was developed for object-orientedprogramming. Because the terms are now commonplace in the object-orienteddocumentation and products, you need to learn and become comfortablewith them in order to work efficiently.<P>In this chapter, you see how to represent objects in Perl usingclasses, methods, and properties. In addition, you look at thedefinitions of some big words such as <I>abstraction</I>, <I>eNCapsulation</I>,<I>inheritaNCe</I>, and <I>polymorphism</I>.<P>Following are short definitions for these words. The sectionsthat follow expand on these definitions and show some examplesof their use.<BLOCKQUOTE><B>Abstraction:</B> Information about an object (its properties)can be accessed in a manner that isolates how data is stored fromhow it is accessed and used.</BLOCKQUOTE><BLOCKQUOTE><B>ENCapsulation:</B> The information about an object and fuNCtionsthat manipulate the information (its methods) are stored together.</BLOCKQUOTE><BLOCKQUOTE><B>InheritaNCe:</B> Classes can inherit properties and methodsfrom one or more parent classes.</BLOCKQUOTE><BLOCKQUOTE><B>Polymorphism:</B> A child class can redefine a method alreadydefined in the parent class.</BLOCKQUOTE><H2><A NAME="LearningaboutClasses"><FONT SIZE=5 COLOR=#FF0000>Learning about Classes</FONT></A></H2><P>Before looking at specific examples of object-oriented Perl code,you need to see some generic examples. Looking at generic exampleswhile learning the &quot;standard&quot; object-oriented terminologywill ensure that you have a firm grasp of the coNCepts. If youhad to learn new Perl coNCepts at the same time as the objectcoNCepts, something might be lost because of information overload.<P><I>Classes</I> are used to group and describe object types. Rememberthe character classes from <A HREF="ch10.htm" >Chapter 10</A>, &quot;Regular Expressions&quot;?A class in the object-oriented world is essentially the same thing.Let's create some classes for an inventory system for a pen andpeNCil vendor. Start with a pen object. How could you describea pen from an inventory point of view?<P>Well, the pen probably has a part number, and you need to knowhow many of them there are. The color of the pen might also beimportant. What about the level of ink in the cartridge-is thatimportant? Probably not to an inventory system because all thepens will be new and therefore full.<P>The thought process embodied in the previous paragraph is called<I>modeling</I>. Modeling is the process of deciding what willgo into your objects. In esseNCe, you create a model of the worldout of objects.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Tip</B></TD></TR><TR><TD><BLOCKQUOTE>The terms <TT><I>object</I></TT> and <TT><I>class</I></TT> are pretty interchangeable. Except that a class might be considered an object described in computer language, whereas an object is just an object.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Objects are somewhat situationally dependent. The descriptionof an object, and the class, depends on what needs to be done.If you were attempting to design a school course scheduling program,your objects would be very different than if you were designinga statistics program.<P>Now back to the inventory system. You were reading about pensand how they had colors and other identifying features. In objecttalk, these features are called <I>properties</I>. Figure 14.1shows how the pen class looks at this stage of the discussion.<P><A HREF="f14-1.gif"><B>Figure 14.1 : </B><I>The Pen Class and its properties</I>.</A><P>Now that you have a class, it's time to generalize. Some peoplegeneralize first. I like to look at the details first and thenextract the common information. Of course, usually you'd needseveral classes before any common features will appear. But becauseI've already thought this example through, you can cheat a little.<P>It's pretty obvious that all inventory items will need a partnumber and that each will have its own quantity-on-hand value.Therefore, you can create a more general class than Pen. Let'scall it <TT>Inventory_item</TT>. Figure14.2 shows this new class.<P><A HREF="f14-2.gif"><B>Figure 14.2 : </B><I>The Inventory_item class and its properties</I>.</A><P>Because some of <TT>Pen's</TT> propertiesare now also in <TT>Inventory_item</TT>,you need some mechanism or technique to avoid repetition of information.This is done by deriving the <TT>Pen</TT>class from <TT>Inventory_item</TT>.In other words, <TT>Inventory_item</TT>becomes the <I>parent</I> of <TT>Pen</TT>.Figure 14.3 shows how the two classes are now related.<P><A HREF="f14-3.gif"><B>Figure 14.3 : </B><I>The relationship between Inventory_itemand Pen</I>.</A><P>You may not have noticed, but you have just used the coNCept of<I>inheritaNCe</I>. The <TT>Pen</TT>class inherits two of its properties from the <TT>Inventory_item</TT>class. InheritaNCe is really no more complicated than that. Thechild class has the properties of itself plus whatever the parentclass has.<P>You haven't seen methods or fuNCtions used in classes yet. Thiswas deliberate. Methods are inherited in the same way that datais. However, there are a couple of tricky aspects of using methodsthat are better left for later. Perhaps even until you start lookingat Perl code.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>Even though you won't read about methods at this point in the chapter, there is something important that you need to know about inheritaNCe and methods. First, methods are inherited just like properties. Second, using inherited methods helps to create your program more quickly because you are using fuNCtionality that is already working. Therefore-at least in theory-your programs should be easier to create.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="AbstractThinking"><FONT SIZE=5 COLOR=#FF0000>Abstract Thinking</FONT></A></H2><P>Earlier, I mentioned the term <I>abstraction</I>. Let's examinethe idea a little further. In order to do this, you need a workingdefinition of the term <I>model</I>. How about, &quot;A modelis an approximation of something.&quot; If you build a model car,some of the items in the original car will be missing, such asspark plugs, for example. If you build a model house, you wouldn'tiNClude the plumbing. Thus, the models that you build are somewhatabstract; the details don't matter, just the form.<P>Abstraction in object-oriented programming works in the same way.As the programmer, you present the model of your objects to otherprogrammers in the form of an <I>interface</I>. Actually, theinterface is just some documentation that tells others how tointeract with any of your classes. However, nobody needs to knowwhat your classes really do. It is enough to say that the fileobject stores the file name and size and presents the informationin English. Whether the internal format of the information iscompressed, Russian, or stored in memory or on the hard disk isimmaterial to the user of your classes.<P>I recommend that as you design an object or class, you occasionallydistaNCe yourself from the work. Try to view the resulting systemthrough the eyes of another to check for iNConsisteNCies and relationshipsthat aren't needed.<P>You've learned about abstraction in abstract terms so far. Nowlet's use the <TT>Pen</TT> class thatyou created earlier to see a coNCrete example of abstraction.The <TT>Pen</TT> class had only oneproperty of its own, the ink color (the rest were inherited).For the sake of argument, the ink color can be <TT>&quot;blue,&quot;</TT><TT>&quot;black,&quot;</TT> or <TT>&quot;red.&quot;</TT>When a <TT>Pen</TT> object is created(the mechanism of creation is unimportant at the moment), a specificcolor is assigned to it. Use <TT>&quot;blue&quot;</TT>for the moment. Here is a line of code to create the object:<BLOCKQUOTE><PRE>$pen = Pen-&gt;new(&quot;blue&quot;);</PRE></BLOCKQUOTE><P>Now the <TT>Pen</TT> object has beencreated. Do you care if the internal format of the ink color isthe string <TT>&quot;blue&quot;</TT>or the number 1? What if, because you expect to use thousandsof objects, the internal format changes from a string to a numberto save computer memory? As long as the interface does not change,the program that uses the class does not need to change.<P>By keeping the external interface of the class fixed, an abstractionis being used. This reduces the amount of time spent retrofittingprograms each time a change is made to a class the program isusing.<H2><A NAME="OverridingMethodswithPolymorphism"><FONT SIZE=5 COLOR=#FF0000>Overriding Methods with Polymorphism</FONT></A></H2><P><I>Polymorphism</I> is just a little more complicated than inheritaNCebecause it involves methods. Earlier, I said you might not learnabout methods before you look at a real object-oriented Perl program,but I changed my mind. Let's make up some methods that belongin an inventory program. How about a method to print the propertiesfor debugging purposes or a method to change the quantity-on-handamount? Figure 14.4 shows the <TT>Inventory_item</TT>class with these two fuNCtions.<P><A HREF="f14-4.gif"><B>Figure 14.4 : </B><I>The Inventory_item class with methods</I>.</A><P>This new fuNCtion is automatically inherited by the <TT>PEN</TT>class. However, you will run into a problem because the <TT>printProperties()</TT>fuNCtion won't print the ink color. You have three choices:<UL><LI>Change the fuNCtion in the <TT>Inventory_item</TT>class-This is a bad choice because the generic inventory itemshould not know any unique information about inventory objects-justgeneral or common information.<LI>Create a new fuNCtion in the <TT>Pen</TT>class called <TT>printPenProperties()-</TT>Thisis another bad choice. By solving the problem this way, everyclass will soon have its own print fuNCtions, and keeping trackof the fuNCtion names would be a nightmare.<LI>Create a new fuNCtion in the <TT>Pen</TT>class called <TT>printProperties()</TT>to <I>override</I> the definition from <TT>Inventory_item</TT>.This is a good solution. In fact, this is the way that polymorphismworks.</UL><P>Perl's take on polymorphism is that if you call a method in yourprogram, either the current class or a parent class should havedefined that method. If the current class has not defined themethod, Perl looks in the parent class. If the method is stillnot found, Perl continues to search the class <I>hierarchy</I>.<P>I can hear you groaning at this point-another object-orientedword! Yes, unfortunately. But at least this one uses the normal,everyday definition of the word. A <I>hierarchy</I> is an organizedtree of information. In our examples so far, you have a two-levelhierarchy. It's possible to have class hierarchies many levelsdeep. In fact, it's quite common. Figure 14.5 shows a class hierarchywith more than one level.<P><A HREF="f14-5.gif"><B>Figure 14.5 : </B><I>A class hierarchy with many levels</I>.</A><P>It's probably worth mentioning that some classes contain onlyinformation and not methods. As far as I know, however, thereis no special terminology to reflect this. These information-onlyclasses may serve as adjuNCt or helper classes.<H2><A NAME="KeepingCodeandDataTogetherwithENCapsulation"><FONT SIZE=5 COLOR=#FF0000>Keeping Code and Data Together with ENCapsulation</FONT></A></H2><P>There's not much that I need to say about eNCapsulation. Keepingthe methods in the same place as the information they affect seemslike common sense. It wasn't done using earlier languages mostlybecause the programming tools were not available. The extra workrequired to manually perform eNCapsulation outweighed the benefitsthat would be gained.<P>One big advantage of eNCapsulation is that it makes using informationfor unintended purposes more difficult, and this reduces logicerrors. For example, if pens were sold in lots of 100, the <TT>changeQuantityOnHand()</TT>fuNCtion would reflect this. Changing the quantity by only onewould not be possible. This enforcement of business rules is oneof the biggest attractions of object-oriented programming.<H2><A NAME="HowPerlHandlesObjects"><FONT SIZE=5 COLOR=#FF0000>How Perl Handles Objects</FONT></A></H2><P>Remember the coNCept of refereNCes that was discussed in <A HREF="ch8.htm">Chapter8</a>, &quot;RefereNCes&quot;?  If not, please re-read it. RefereNCeswill play a large role in the rest of the chapter and are criticalto understanding how classes are used. You specifically need toremember that the <TT>{ }</TT> notationindicates an anonymous hash. Armed with this knowledge and theobject-oriented terminology from the first part of this chapter,you are ready to look at real Perl objects. Listing 14.1 showsyou how the <TT>inventory_item</TT>class could be defined in Perl.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE>

⌨️ 快捷键说明

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