📄 ch14.htm
字号:
<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 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, "What are objects?" is a silly question because
you already know what an object is. Trust your instiNCts. The
book you are reading is an object. The knife and fork you eat
with are objects. In short, your life is filled with them.
<P>
The question that really needs to be asked is, "What are
classes?" You see, all object-oriented techniques use classes
to do the real work. A <I>class</I> is a combination of variables
and fuNCtions designed to emulate an object. However, when referring
to 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-oriented
programming. Because the terms are now commonplace in the object-oriented
documentation and products, you need to learn and become comfortable
with them in order to work efficiently.
<P>
In this chapter, you see how to represent objects in Perl using
classes, methods, and properties. In addition, you look at the
definitions 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 sections
that follow expand on these definitions and show some examples
of their use.
<BLOCKQUOTE>
<B>Abstraction:</B> Information about an object (its properties)
can be accessed in a manner that isolates how data is stored from
how it is accessed and used.
</BLOCKQUOTE>
<BLOCKQUOTE>
<B>ENCapsulation:</B> The information about an object and fuNCtions
that manipulate the information (its methods) are stored together.
</BLOCKQUOTE>
<BLOCKQUOTE>
<B>InheritaNCe:</B> Classes can inherit properties and methods
from one or more parent classes.
</BLOCKQUOTE>
<BLOCKQUOTE>
<B>Polymorphism:</B> A child class can redefine a method already
defined 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 examples
while learning the "standard" object-oriented terminology
will ensure that you have a firm grasp of the coNCepts. If you
had to learn new Perl coNCepts at the same time as the object
coNCepts, something might be lost because of information overload.
<P>
<I>Classes</I> are used to group and describe object types. Remember
the character classes from <A HREF="ch10.htm" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/ch10.htm" >Chapter 10</A>, "Regular Expressions"?
A class in the object-oriented world is essentially the same thing.
Let's create some classes for an inventory system for a pen and
peNCil vendor. Start with a pen object. How could you describe
a pen from an inventory point of view?
<P>
Well, the pen probably has a part number, and you need to know
how many of them there are. The color of the pen might also be
important. What about the level of ink in the cartridge-is that
important? Probably not to an inventory system because all the
pens 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 will
go into your objects. In esseNCe, you create a model of the world
out 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 description
of 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 designing
a statistics program.
<P>
Now back to the inventory system. You were reading about pens
and how they had colors and other identifying features. In object
talk, these features are called <I>properties</I>. Figure 14.1
shows how the pen class looks at this stage of the discussion.
<P>
<A HREF="f14-1.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/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 people
generalize first. I like to look at the details first and then
extract the common information. Of course, usually you'd need
several classes before any common features will appear. But because
I've already thought this example through, you can cheat a little.
<P>
It's pretty obvious that all inventory items will need a part
number and that each will have its own quantity-on-hand value.
Therefore, you can create a more general class than Pen. Let's
call it <TT>Inventory_item</TT>. Figure
14.2 shows this new class.
<P>
<A HREF="f14-2.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/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> properties
are 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" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/f14-3.gif"><B>Figure 14.3 : </B><I>The relationship between Inventory_item
and 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. The
child class has the properties of itself plus whatever the parent
class has.
<P>
You haven't seen methods or fuNCtions used in classes yet. This
was deliberate. Methods are inherited in the same way that data
is. However, there are a couple of tricky aspects of using methods
that are better left for later. Perhaps even until you start looking
at 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 examine
the idea a little further. In order to do this, you need a working
definition of the term <I>model</I>. How about, "A model
is an approximation of something." If you build a model car,
some of the items in the original car will be missing, such as
spark plugs, for example. If you build a model house, you wouldn't
iNClude the plumbing. Thus, the models that you build are somewhat
abstract; 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 other
programmers in the form of an <I>interface</I>. Actually, the
interface is just some documentation that tells others how to
interact with any of your classes. However, nobody needs to know
what your classes really do. It is enough to say that the file
object stores the file name and size and presents the information
in English. Whether the internal format of the information is
compressed, Russian, or stored in memory or on the hard disk is
immaterial to the user of your classes.
<P>
I recommend that as you design an object or class, you occasionally
distaNCe yourself from the work. Try to view the resulting system
through the eyes of another to check for iNConsisteNCies and relationships
that aren't needed.
<P>
You've learned about abstraction in abstract terms so far. Now
let's use the <TT>Pen</TT> class that
you created earlier to see a coNCrete example of abstraction.
The <TT>Pen</TT> class had only one
property of its own, the ink color (the rest were inherited).
For the sake of argument, the ink color can be <TT>"blue,"</TT>
<TT>"black,"</TT> or <TT>"red."</TT>
When a <TT>Pen</TT> object is created
(the mechanism of creation is unimportant at the moment), a specific
color is assigned to it. Use <TT>"blue"</TT>
for the moment. Here is a line of code to create the object:
<BLOCKQUOTE>
<PRE>
$pen = Pen->new("blue");
</PRE>
</BLOCKQUOTE>
<P>
Now the <TT>Pen</TT> object has been
created. Do you care if the internal format of the ink color is
the string <TT>"blue"</TT>
or the number 1? What if, because you expect to use thousands
of objects, the internal format changes from a string to a number
to 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 abstraction
is being used. This reduces the amount of time spent retrofitting
programs each time a change is made to a class the program is
using.
<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 inheritaNCe
because it involves methods. Earlier, I said you might not learn
about methods before you look at a real object-oriented Perl program,
but I changed my mind. Let's make up some methods that belong
in an inventory program. How about a method to print the properties
for debugging purposes or a method to change the quantity-on-hand
amount? Figure 14.4 shows the <TT>Inventory_item</TT>
class with these two fuNCtions.
<P>
<A HREF="f14-4.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/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 item
should not know any unique information about inventory objects-just
general or common information.
<LI>Create a new fuNCtion in the <TT>Pen</TT>
class called <TT>printPenProperties()-</TT>This
is another bad choice. By solving the problem this way, every
class will soon have its own print fuNCtions, and keeping track
of 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 polymorphism
works.
</UL>
<P>
Perl's take on polymorphism is that if you call a method in your
program, either the current class or a parent class should have
defined that method. If the current class has not defined the
method, Perl looks in the parent class. If the method is still
not found, Perl continues to search the class <I>hierarchy</I>.
<P>
I can hear you groaning at this point-another object-oriented
word! Yes, unfortunately. But at least this one uses the normal,
everyday definition of the word. A <I>hierarchy</I> is an organized
tree of information. In our examples so far, you have a two-level
hierarchy. It's possible to have class hierarchies many levels
deep. In fact, it's quite common. Figure 14.5 shows a class hierarchy
with more than one level.
<P>
<A HREF="f14-5.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/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 only
information and not methods. As far as I know, however, there
is no special terminology to reflect this. These information-only
classes 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. Keeping
the methods in the same place as the information they affect seems
like common sense. It wasn't done using earlier languages mostly
because the programming tools were not available. The extra work
required to manually perform eNCapsulation outweighed the benefits
that would be gained.
<P>
One big advantage of eNCapsulation is that it makes using information
for unintended purposes more difficult, and this reduces logic
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -