Está en la página 1de 20

Bits & Bytes: Lesson 2 Things, Things, and More Things

The world through the eyes of a computer


It will come as no surprise to you that the world is far more complex than it was just a short time ago. For just a moment, step back in time with me. The year is 19 ! and "orld "ar II is raging. # secret military project is underway to create a computer to calculate the trajectory of artillery shells. This computer, named $%I#& '$lectronic %umerical Integrator and &alculator(, performs in )* minutes the math that would take humans ! days to sol+e, The $%I#& was o+er 1** feet long, circling a room !* feet by -* feet. It was 1* feet high and about ! feet deep and weighed about !* tons. It contained o+er 1.,*** +acuum tubes and programs had to be physically wired into the computer.

The $%I#& / 01 #rmy 2hoto

3its and 3ytes4 5esson )

The $%I#& used numeric data such as the wind direction and speed, plus the +elocity of the shell, to calculate the shell6s flight to the target. "hile that was 7uite a feat in 19 !, such calculations are common today and occur almost instantaneously in modern computer games. %eedless to say, today6s complex world re7uires considerably more sophistication and power from computers. "e ha+e come to rely upon technology and computers for much in our daily li+es 8 directly in our careers or education, and indirectly through our systems of communication and transportation, our choices in entertainment and recreation, and in essential ser+ices such as food production and health care. The tasks performed by computers today in+ol+e more than just mathematical calculations. They track airplanes in flight, predict weather conditions, store huge 7uantities of data in the form of +ideo, graphics and text, coordinate the deli+ery of products from around the world to markets, and much, much more. In fact, I challenge you to think of one business process or ser+ice that is not in some way managed by a computer. The changing needs of a global society and the complexity of keeping it all under control and manageable ha+e changed the way in which programmers think about problems that can be sol+ed with a computer.

In 5esson 1 of this series / 2roblem 1ol+ing in 5ife and Technology / you categori9ed problems, selected solution strategies to fit specific problems, and fine8tuned your personal problem sol+ing skills. In 5esson ) we are going to examine more closely the process of creating a computer solution for a problem. :ou will experience a new thinking style, which mimics the thinking of computer scientists as they tackle complicated problems. 1o let6s begin exercising our brain in this new way.

Understanding Ob ect!Oriented "esign


From the work of computer scientists sol+ing complex problems in the 19.*6s, a new way of thinking about sol+ing problems with computers e+ol+ed. This new thinking style allows programmers to create organi9ed programs to sol+e 8# style of thinking difficult problems, in+ol+ing interactions between, and which focuses on dependencies upon, +arious entities. This thinking style has modeling a real8world become known as ;bject8;riented <esign ';;<(. =ather system and the than primarily focusing on the tasks re7uired to sol+e a problem and the order in which to perform these tasks, ;;< focuses on modeling a real8world system and the associated objects in that world to arri+e at a solution. "ith this shift in thinking, we analy9e problems by deciding what entities, things, or objects are in+ol+ed in the situation and what each object must do in order to sol+e the problem at hand. Ob ect!Oriented "esign 2rocedural thinking is a step8by8step process with a definite starting point and definite ending point. It6s like knitting a sweater> start with a ball of yarn, perform specific steps, and end up with a sweater, 2rocedural thinking looks like this4

1tep 1tep 1 1

1tep 1tep ) )

1tep 1tep ! !

3its and 3ytes4 5esson )

;bject8;riented <esign focuses upon relationships between the ?things@ in+ol+ed in sol+ing a problem. The order in which the ?things@ interact, the number of times they interact, and the specifics of the details of the interactions can +ary with the situation. ;b+iously this approach is most fitting to complex problems for which the outcomes can +ary depending upon the needs of the user. 5et me gi+e you an example of a complex problem, but one you ha+e likely encountered, which can be thought about in an ;;< style. The <epartment of Aotor Behicles '<AB( maintains records about you and your +ehicles. 2erhaps you ha+e se+eral different +ehicles such as a car, a truck, or a boat and trailer. "riting a computer program to handle all of this for your +ehicle, as well as for thousands of other +ehicles, is +ery complex. In addition to keeping track of your +ehicles, there are interactions between the <AB and the legal system, as well as with insurance companies. :ou likely are issued your operator6s license by the <AB. In some states the records of +oter registration and organ donors are processed and passed along by the <AB. "hen analy9ed like this, what at first seemed like simple bookkeeping becomes a complex problem in+ol+ing many interactions with, and dependencies upon, other entities. ;bject8;riented thinking looks more like this4

The Insurance &ompany

The 5egal 1ystem

:our Behicle ;rgan <onor =egistry 5icense 2late Aanufacturer

&omplex problems with interactions and dependencies are most easily sol+ed with ;;< because this is the way humans think. "e analy9e and plan and resol+e issues in our li+es by concentrating on ?things@, or objects. If you are planning a trip, you think about cars, maps, restaurants, hotels, and attractions. If you are planning a new business you think about products, employees, ad+ertisements, bank accounts, and customers. This is just the !

3its and 3ytes4 5esson )

way we process the tasks of daily life, large and small. It is also a comfortable way to de+elop computer solutions for complex problems. #racticing OO" #s the name suggests, this style of designing computer programs focuses on objects. 1ince we intellectually build concepts, or mental images, about ?things@ in our world, this beha+ior is 7uite natural. =ight now, close your eyes and ?think@ about your car. "ithout any effort at all, you en+ision its color, make, interior, and transmission. :ou probably 7uite easily anticipate its capabilities in terms of mo+ing forward, backwards, and braking. %ow, en+ision / design in your mind / your dream car of the future. "hat name would you gi+e itC "hat color is itC "hat kind of roof does it ha+eC Dow fast does it goC &an it flyC Dow does it na+igateC <oes it interact with other carsC <oes it recogni9e youC Euess what, :ou just created an abstract object by thinking in an ;;< style,

:ou are sol+ing a transportation need by designing a solution with an object that has properties such as a color and a name, and that has capabilities such as going fast, flying, and recogni9ing its owner. In addition, you thought about the car6s interactions with other cars on the road and its dependency upon some na+igational system. This is the kind of thinking that computer programmers use to create solutions to problems, also. Think again about the <AB scenario described earlier in this lesson. 5et6s design a solution for the problem of processing thousands of +ehicle registrations in the same way a programmer might design it with this ;bject8;riented <esign focus. =ecall that the $ircle!Bac% problem sol+ing strategy learned in 5esson 1 has three steps which repeat until the problem is sol+ed. #fter the initial step of Representing the Problem by defining the goals, a few 7uestions must be answered in order to de+ise a possible solution in the Searching for Solutions step. 1. 2rogrammers using the ;;< process first ask, ?"hat objects should be created to sol+e this problemC@ In this simplified <AB example it is fairly clear that a +ehicle registration object will be able to do most of the tasks re7uired. In a more complex and realistic problem, perhaps other objects would also be needed for issuing operator permits and for communication between the +ehicle, the +ehicle owner, and other entities. 3ut for now, let6s consider a simplified <AB scenario with +ery basic +ehicle registration processes. ). The second 7uestion asked is, ?"hat properties should my objects ha+eC@

3its and 3ytes4 5esson )

# property is a defining characteristic. ;bjects ha+e many properties. # +ehicle registered with the <AB has properties essential for this problem such as the +ehicle identification number, the state in which it6s registered, the year, make, and model, the owner6s name and address, and fees paid. #roperty The combination of all of these properties defines a specific and uni7ue +ehicle registration / your +ehicle6s registration. 8 # defining It is important to select only the properties a +ehicle must characteristic of an ha+e to complete the problem associated with registering in object that is critical to your state. $xtra details that are not critical to the solution sol+ing the problem. are not needed. !. Finally the programmer asks, ?"hat abilities must a +ehicle ha+e to do the work expected of it in this scenarioC@ In computer8talk these abilities are called beha+iors or methods. ;b+iously, to do the work expected of it at the <AB, a +ehicle must be able to calculate annual fees, send renewal notices to the owners, issue a license plate number, report traffic +iolations to the insurance company, print a registration receipt for your glo+e box, and maybe e+en communicate with the authorities if it is reported stolen.

Method 8 The ability or beha+ior an object must possess to sol+e a problem.

& 'egistered (ehicle


#roperties 1FFG3- :1"0FF! 'BI%( Idaho 'state( )**F Ford 3ronco 'year, make, and model( Gim :oung 'owner( )- . Aain 1treet 'address( H)F..** 'fees( Methods 0pdate information &alculate annual fees 1end renewal notice Issue a license =eport to insurance company 2rint a registration receipt &ommunicate with law

3its and 3ytes4 5esson )

;ne of the principles of ;bject8;riented <esign, is the idea that each object should be independent, self8sufficient and wrapped up into a neat package. Think about your personal auto. "hen you turn the key, the car can start on its own / it doesn6t need to interface with other objects such as an *ncapsulation auto mechanic for this to happen 'or it shouldn6t,( :ou also 8 The concept of don6t need to look under the hood to see all the engine6s allowing access to the inner workings to make the car do things. The same ideas properties and methods apply to computer programs. $ncapsulation insures that the of an object through properties of objects are only modified by methods of the interactions with the object. The job of maintaining ;;< programs is simplified class itself. because any changes that are re7uired are isolated due to encapsulation. #ny changes to the properties or methods of an object are confined to the object. #s you learn more about programming you will recogni9e why this is so important for efficient and bug8free programs.

5et6s re+iew the process for creating an object8oriented design4 1. "hat objects should be created to sol+e this problemC ). "hat characteristics or properties should my objects ha+eC !. "hat abilities or methods must my objects ha+e to do the work expected of themC &bstraction
!The

process of identifying the essential problem details and their relationships from the problem.

This !8step 7uestioning process gets at the essential properties and the re7uired methods of an object necessary to sol+e a problem. The resulting description of an object is called an abstraction. "e abstracted / or identified / the essential elements of a +ehicle by defining the necessary properties and methods re7uired to sol+e the problem of handling +ehicle registrations at the <AB.

)et 'eal

5et6s ha+e some fun with the process of ;bject8;riented <esign. Imagine that you are the director of the local animal shelter. $ach year you sponsor a pet show for the pets owned by local children, and you are responsible for keeping track of all the winners of the +arious competitions. There are hundreds of pets and each can compete in up to four competiti+e e+ents. 2ets can earn monetary pri9es for each e+ent and the total amount awarded to any one pet is used to determine the ?2et $xtraordinaire@ designation for high8scoring pets. The owners are recogni9ed with certificates and checks for their winnings. #naly9e this problem by focusing on objects that can represent the +arious elements of the I

3its and 3ytes4 5esson )

pet show and perform the work needed to sol+e this problem. 1. "hat object's( should be created to sol+e this problemC ). "hat properties should my object's( ha+eC !. "hat abilities must the object's( ha+e to do the work expected of itC

:our ;bject8;riented <esign might be different than mine> that6s one of the great things about designing software / there are numerous solutions to achie+e the goals. :ou6re limited only by your own creati+ity and your willingness to learn new skills. 1. # ?pet@ object should be defined because this is the basic entity that can compete in e+ents, win money and recei+e awards. If you are +ery analytical, you might ha+e decided that there could also be other objects such as an owner, a competition, a certificate and a check. "e6ll keep things simple and just use 1 object. ). 2ets ha+e many ob+ious properties. The trick is to select only those which ha+e some bearing upon the problem to be sol+ed. "hile a pet has a color and a fa+orite toy, these properties are not necessary for sol+ing the problem at hand so they should not be included. The ob+ious details re7uired include the pet6s name, the pet6s owner6s name, the competiti+e e+ents the pet is participating in 'maximum of (, the pri9e amount won 'if any( for each competition, and the total winnings. :ou will notice that the name of the owner is needed for printing the check and the certificate. In addition, you should recogni9e the need for a uni7ue identifier such as an entry number I< for each pet because there could be do9ens of pets with the name ?Fluffy@ who6s owner is ?Jim@ !. The pet object needs to be able to set the amount of its pri9e for each competition as it occurs during the day and to calculate the total winnings. #dditionally, the pet object must determine if the ?2et $xtraordinaire@ designation applies to itself, and it must print a certificate and a check. These abilities would be defined within methods written in the code of the class.

3its and 3ytes4 5esson )

& #et
#roperties Fluffy 'pet name( Jim 'owner( 3est trick 'e+ent 1( 1st place H1* 'pri9e( Erooming 'e+ent )( !rd place H- 'pri9e( H1- 'calculate winnings( Methods 1et amount of pri9es for each category &alculate total winnings <etermine ?2et $xtraordinaire@ designation 2rint certificate 2rint check

3its and 3ytes4 5esson )

"efining Ob ects with $lasses


In a computer program created in the ;bject8;riented <esign ';;<( style, programmers translate these abstractions into the code of a specific computer language. The code which describes all of the object6s properties and methods is called a class. "e can think of a &lass as the blueprint, and an ;bject as an instance 'or specific $lass example( of that &lass such as the house down the street. # computer code segment that describes an object6s properties and methods.
!

To sol+e the <AB problem we must create a ?+ehicle@ class which defines all of the properties of a ?+ehicle@ object, and lists the steps to be executed in each of its methods, necessary for the tasks of registration. The class in this <AB example would be named ?Behicle.@ The name of a class is capitali9ed. &lasses are typically segments of larger programs. <on6t worry that you do not yet understand how these segments are combined into working programs. The pieces will come together as you learn more and ha+e the opportunity to study a particular computer programming language. Dere is an example of the Behicle class described in pseudo8code 'human8readable words(4 Class Vehicle Property Vehicle_Identification_Number Property Owner_Name Method Calculate_ ee !" amount# Method Issue_$icense !" number#

The process of creating code that follows ;;< is referred to as ;bject8;riented 2rogramming ';;2(. I6m only telling you this now because sometimes ;;< and ;;2 are used interchangeably> they essentially mean the same thing / sol+ing problems by focusing on objects with properties and methods which model the situation. Ob ect +actories ;ne way to think about a class is to +isuali9e it as an ?object factory.@ ;b+iously, to be useful, a <AB program must create and access more than one +ehicle registration. In a computer program that models the <AB, the Behicle class ser+es as a factory to produce as many specific +ehicles as needed. :our car registration is defined differently from a motorcycle or a boat registration. $ach of these registrations, with all of its uni7ue details, is stored separately in the computer6s memory. 3ecause of this, each +ehicle can be located in the computerKs memory and manipulated without affecting any other +ehicle. To +isuali9e this, think about an automobile factory. $ach auto is made according to different specifications, depending upon the 9

3its and 3ytes4 5esson )

orders placed. #s each automobile is produced, it6s assigned to a uni7ue storage location in the factory6s parking lot. This is similar to the way a class that creates +ehicle registration objects operates. :ou can think of the automobile factory as a %ew#uto &lass, and each new automobile is an object of type %ew#uto. Eoing back to the <AB example, each +ehicle is made uni7uely to the specifications of a registration order and stored independently of the other +ehicle registrations. $ach +ehicle registration has its indi+idual properties and capabilities that determine its uni7ueness, just as each new automobile in the factory lot has properties that make it uni7ue from all others.

&naly,ing #roblems 1o how many classes do I really need to sol+e a problemC This is a serious design 7uestion. Trying to figure out the object or objects in+ol+ed in a real8world problem that can be modeled in a computer program is a challenge, =emember it takes practice and patience to learn a new thinking style. "hile there are no hard8and8fast rules, the answer can be determined by following these hints and guidelines that make ;;< easier4 Bisuali9e a problem by animating in your mind the actions that must happen as the problem is sol+ed. Turn the process into an animated cartoon. 5et inanimate objects or abstract things ?come to life@ with properties you can see and actions you can witness. The <isney animation antasia pro+ides a good example of inanimate object coming to life. &ount how many different ?things@ in your cartoon are needed to sol+e the problem. These actors in the animation might be the objects that will e+entually become represented by classes. Biew objects with a narrow lens. Focus closely on the essential details of a potential object and ignore extraneous data. Ei+e objects only the most essential properties and methods to address the problem. Aethods that can be described as ?supporting the work of this object@ but not directly tied to the object should be defined in other object types.

=emember, an abstract object is just that / abstract. It is designed to model e+ents in the real world, not duplicate them. 1electing the critical objects in a problem and determining the necessary properties and methods, is a skill that de+elops with practice. <eciding upon the classes for a computer program is a problem with no defined outcome or defined solution. There are multiple solutions to these design 7uestions. The &ircle83ack problem sol+ing strategy works well. There are plenty of opportunities to start back at the beginning. Think of ;bject8;riented <esigning as sol+ing a mystery with clues and relationships of +arying le+els of importance. Jump in, gi+e it a try, and ha+e fun.

)et 'eal

1*

3its and 3ytes4 5esson )

2ractice a little ;;< by thinking about the problem of managing a grocery store in+entory. The manager of the store needs to keep track of the location of products on the shel+es, order replacement products when the supply gets low, remo+e items when the ?sell8by@ date passes, discontinue unpopular items, and pay suppliers. #nimate this problem in your mind by creating a cartoon of ?things@ that act. 1. "hat is the primary object you seeC ). "hat properties do they ha+e that are essential for managing an in+entoryC !. "hat do they doC . "ho or what do they communicate withC -. "hat messages do they recei+e or sendC I. <o these objects need help from other objectsC

3ecause this is a highly creati+e acti+ity and some people ha+e better imaginations than others, your answers will likely be +ery different from mine. That6s great because there are no perfect answers and creati+e problem sol+ing is +alued in computer programming. 1. # +ariety of grocery items4 oranges, cornflakes, salmon, tomato soup, yogurt, etc. ). They possess a 02& code that includes a name, si9e, producer, and price. There is also a shelf locator, deli+ery date, lot number with sell8by date, an ideal 7uantity number, and a number8on8hand +alue. !. These items keep track of the number on hand, order more when the supply is low, send notices when the sell8by date is expired, change their prices, and pay suppliers. . The cash register for printing receipts, the stock workers, the producer -. They send messages to reorder, remo+e from shelf, or discontinue. They recei+e messages from stock workers to change their price, location, or ideal 7uantity to keep on hand. I. :es 8 the cash register, an ordering object, a banking object, a record keeping and printing object.

11

3its and 3ytes4 5esson )

$apturing the power of classes


There are many more concepts and complexities of this powerful ;;< style which you will learn when you begin programming. 3ut for now let6s consider two more ideas which are real power boosters for programmers. $ode 'euse 8 3uilding computer programs with components such as classes which can be applied to similar problems in other programs. #s you might ha+e already guessed, the creation of classes as separate, independent, encapsulated portions of code makes them reusable. If you create a class representing an in+entory item in a grocery store program, the same code could likely be reused in a program for a hardware store or a warehouse company for keeping track of products and in+entory.

&ode reuse enables programmers to work efficiently to build huge, complex programs by assembling different bits of already existing classes into new creations. :ou can think of classes as parts in a 5ego set. # toy wheel can by used in building cars, trucks, mopeds, and more. The fact that code can be reused in many different situations has led to the creation of huge collections of classes called libraries. 2rogrammers can search through these libraries to find just the ?object@ they need. :ou ha+e likely, but unknowingly, encountered code reuse. For example, nearly e+ery computer game, from your fa+orite 1olitaire to 2roject Eotham =acing, employs random numbers. 2rogrammers who need random numbers for their program don6t ha+e to write the code to generate these random numbers themsel+es. They just need to add the random number class to their program, send the correct re7uest message to it, and the class takes care of the rest by producing a random number to be -nheritance 8 # hierarchy of classes in which the properties and methods of the top le+el or parent class extend into each lower le+el or child class. used in the game. The second power booster for ;;< is inheritance of classes. To +isuali9e this, en+ision the diagrams used to represent your branching family tree. %ear the top are Ereat8Ereat8Ereat Erandmother and Erandfather 5ee. $ach downward branch represents the next generation of 5ees, each of 1)

3its and 3ytes4 5esson )

which has inherited many characteristics of the pre+ious generation, but has many uni7ue traits of its own. This same concept is used in computer science to build up and refine the objects created from classes. The easiest example to think about at this stage of your learning is the 2et class we created earlier in this lesson. :ou probably recogni9ed it as being rather simplistic for a pet show, in part because any pet show is going to ha+e more specific animals than just ?pets.@ There will be dogs, cats, birds, and probably e+en a li9ard, or two. For purposes of keeping track of the entrants and their winnings, all of these pets ha+e some traits in common. They each ha+e an owner, a name, and winnings. :ou can imagine a more sophisticated scenario where there are competitions uni7ue to each type of pet. 3irds might compete for the most beautiful feathers and dogs could compete for the best trick. This refinement can be created through class inheritance. "ithout getting bogged down in the programming details at this point, imagine this4 :ou create a 2et class that has all of the properties and methods that are the same for e+ery pet in the show. These would include properties such as its name and owner. %ext, you create a class just for dogs. :ou tell the computer that a dog is just a more sophisticated pet 'you already know that if you own a dog,( and that e+erything that is programmed in the 2et class applies to this <og class. $ssentially a <og ?is a@ 2et. In the <og class you define additional, uni7ue ?dog@ properties such as weight and trick competition earnings. It might e+en ha+e some methods that no other pet has. The same process of defining this ?second generation@ of classes would apply to the &at class and the 5i9ard class. :ou could expand this to an additional le+el of inheritance so that another class / the Eolden =etrie+er class / would inherit from the <og class and the 1iamese class would inherit from the &at class. Inheritance is not limited to just one class inheriting from another class. %umerous classes can inherit so you can add many types of dogs and cats. This how you might +isuali9e the relationships between +arious classes in a pet show4

#et $lass

Li,ard $lass

"og $lass

$at $lass

)olden 'etrie.er $lass

/iamese $lass

$alico $lass

:ou can imagine this same techni7ue used with the <AB registration problem and the Behicle class. If the Behicle class is the ?parent@ class at the top of the hierarchy, there could be ?children@ such as a &ar class, a Truck class, a Aotorcycle class, or a 3oat class. :ou might e+en recogni9e that this could be carried e+en further if we make a 1emi8trailer class the ?child@ of the Truck class. 5ogically it follows that a 1emi8trailer is just a more 1!

3its and 3ytes4 5esson )

speciali9ed form of a Truck. "ith this inheritance techni7ue programmers build powerful, sophisticated, and flexible programs.

3its and 3ytes4 5esson )

This is how you might +isuali9e the relationships between +arious +ehicles registered at the <AB. There are certainly many more types of accounts that you can add to the structure.

(ehicle $lass

$ar $lass

Motorcycle $lass

Truc% $lass

$lassic $lass

/emi!trailer $lass

+arm Truc% $lass

Dere are a couple examples of inheritance described in pseudo8code 'human8readable words(4 Class Siamese Inherits Cat Property eyeColor Class %ruc& Inherits Vehicle Property ma'(eight

)et 'eal

1. Think about your experiences online. "hat objects or tasks ha+e you obser+ed that are repeated in a +ariety of experiences that might be examples of code reuseC ). Imagine you are designing a program to handle the personnel records and payroll for a hospital. 3ecause there are many distinct classifications of employees with uni7ue descriptions and pay schedules you decide to use inheritance as you de+elop the classes for the program. "hat will you name the parent classC "hat are some of the child classes you might want to createC <raw a tree to represent the relationships.

Dere are some possible solutions4 1. :our answers might include such online objects such as ?shopping carts@ and ?registration forms@ that are found on shopping and membership sites. :ou might ha+e mentioned tasks such as shopping checkouts, downloading, and search procedures. ). There are many structures you could design to represent the inheritance relationships among classes representing hospital employees. The actual design 1-

3its and 3ytes4 5esson )

would be influenced by the specific goals of the program. ;ne possibility is to make a generic ?parent0 $mployee class with ?child@ classes of Aedical, ;perations, and Aanagement employees. The next le+el of ?child@ classes might be <octor, %urse, Food 1er+ice, &ustodian, #dministration, and &lerical employees. The important consideration is that each ?child@ class inherits properties and methods of its parent class and represents a greater le+el of refinement through its uni7ue properties and methods.
*mployee $lass

Medical $lass

Operations $lass

Managers $lass

"octor $lass

1urse $lass

+ood /er.ice $lass

$ustodial $lass

&dmin $lass

$lerical $lass

1I

3its and 3ytes4 5esson )

$+ents and Aessages


$+ents and messages are two concepts +ital to actually using objects in a computer program. #n e+ent as defined in computer science is not too different from your own personal definition of the term ?e+ent.@ #n e+ent in the context of computer science, and in daily life, means ?something happened to catch my *.ent attention.@ #n example of an e+ent in daily life would be a lightning strike or the ring of a doorbell. $ach of these 8 #n action such as a e+ents would catch your attention and perhaps cause some mouse click or a key response from you. In computer science, the click of a press which is mouse or tap of a key is an e+ent. 5ikewise, the computer recogni9ed by a program will take notice and might respond to the e+ent if it has and may prompt some been instructed to do so by the action by the program. program that is currently running. Just as you would not likely respond to the neighbor6s ringing doorbell, the computer doesn6t necessarily respond to e+ery mouse click or key tap that occurs. # message is an instruction sent to an object at the occurrence of an e+ent that re7uests the object to perform one of its methods.

To better understand this concept of e+ents and why it6s important to ;;<, let6s look o+er the shoulder of a <AB clerk as he or she interacts with a customer. The interaction might go like this4 $ler%4 ?Dello. "hat can I do for you todayC@ $ustomer4 ?I would like to renew my +ehicle registration.@ $ler%4 ?"hat is your license number, pleaseC@ $ustomer4 ?!.-8&JG@ $ler%4 $nters the numbers !.-8&JG into a field on the computer screen and clicks on a ?Find =egistration@ button. 3ehind the scenes the button click action by the clerk is interpreted by the computer as an e+ent / Ta8<a, 1omething happened, 3ecause of the code in the +ehicle registration program, the computer responds by sending a message to the computer system to find in its memory the specific and uni7ue +ehicle object associated with this number. %ext it sends a message to that specific +ehicle to display some of its properties on the screen where the teller sees Gim6s name, address, and description of the +ehicle and the calculated the registration fee. $ler%4 ?This year6s fee is H1.*.**. Das any information changed in regard to this +ehicle, GimC@ $ustomer4 ?:es, my address has changed. I now li+e at )! 1. %ew Da+en 1treet.@ $ler%4 $nters ?)! 1. %ew Da+en 1treet@ into a field and clicks on the ?0pdate ;wner Information@ button. #nother button click e+ent has occurred and a message is sent to the +ehicle object to change the recorded address of the owner. #nd perhaps yet another message is sent to this 1F

3its and 3ytes4 5esson )

+ehicle object to send its updated owner information, as well as the renewed registration to the printer. $ler%4 ?:our registration has been renewed and your address changed. Dere is your new registration copy for the glo+e box.@ $ustomer4 ?Thank you@ $ler%4 ?:ou6re welcome, Gim. 2lease come again@ &licks on the ?$nd Transaction@ button initiating another e+ent which sends a message to the system to close access to this particular +ehicle. Dow does this occur inside the codeC #fter a programmer writes the code for the Behicle class '?+ehicle@ object factory( to create these +ehicle registration objects, he or she creates another segment of code called the graphical user interface 'E0I( which interacts with the class, and objects created from the class, through messages. The graphical user interface is the part of the program +isible to the user / in this case, the <AB clerk. "hen a +ehicle owner registers a new +ehicle, the clerk uses the E0I part of the program as a tool to call upon the class by sending a message to create a specific +ehicle object with a uni7ue set of +ehicle properties for this specific customer. In computer -nstantiation terms, this step to create new, uni7ue objects and store them in memory is called instantiation. The Behicle class 8 The creation of a new creates an ?instance@ of the class. This instance is the object from object. In other words, the Behicle class creates a new specifications described +ehicle object based upon the specific ?blueprint@ for a in a class. +ehicle as defined in this ?+ehicle factory@ class and stores it in the computer memory. This is what the code to create a new object from the Behicle class looks like in pseudo8code 'human8readable words(4 Create MyCar as a new Vehicle!list of property )alues# &onceptually, the clerk uses the graphical user interface to trigger e+ents which send messages to the class. These messages can be commands either to classes to create new objects, or to pre+iously created objects to execute methods. In the <AB example, the clerk uses the application by entering information and clicking on buttons which create e+ents that cause messages to be sent to the Behicle class to create new +ehicle registrations or to record transactions for a specific registration. ;ccasionally a message sent to an object must carry with it some additional details. # ?0pdate Information@ message sent to a specific Behicle object must carry with it new information about the persons name or address. This additional information sent with a message is called a parameter. #arameter 8 # +alue sent to a method with a message that is needed to perform the work of the method.

This is what the code to send additional information in the form of a parameter looks like in pseudo8code when the message to update information is sent to a specific +ehicle4 MyCar*+pdateInformation!)! 1. %ew Da+en 1treet#

1.

3its and 3ytes4 5esson )

)et 'eal

5et6s explore e+ents, messages, and parameters in a common computer application. 1. ;pen Aicrosoft "ord or other word processor. "rite a short paragraph describing your understanding of ;;< at this time. ). %ow experiment with some of the common commands you use as you edit in a word processor. &omplete the chart below.

Tas% Find

*.ent

Message

#arameter

Insert hyperlink

0nderlining text

3ecause there are se+eral ways to perform the indicated tasks your answers will likely +ary from the answers below. The important concept is to analy9e what e+ent you are triggering, the message being sent to the computer by that e+ent, and the additional data or parameters the computer will need to complete the intended task.

Tas% Find

*.ent Aouse click $nter Gey pressed

Message ;pen find dialog box 1earch through text ;pen link dialog box #dd link to text 1elect chosen text 0nderline text

#arameter %one &haracters to find %one 0=5 %one 1elected characters

Insert hyperlink

Aouse click =eturn

0nderlining text

Aouse click L drag Aouse click on U

19

3its and 3ytes4 5esson )

/ummary
;bject8;riented <esign ';;<( is a style of analy9ing a complex problem by focusing on the ?objects@ in+ol+ed in the solution. Three 7uestions are asked in analy9ing a problem4 1. "hat objects should be created to sol+e this problemC ). "hat properties should the objects ha+eC !. "hat abilities must the object ha+e to do the work expected of itC The process of abstraction in+ol+es identifying the essential traits of an object that are necessary for the solution. 2roperties are the defining characteristics of an object and methods are the beha+iors or abilities of an object needed to sol+e the problem. ;bjects are defined and encapsulated in code segments called classes. &lasses contribute to efficient programming because they can be reused in many different programs. &reating a new object from a class is called instantiation. Inheritance enables programs to reuse code and to extend general classes into more speciali9ed classes. &hild classes inherit properties and methods from parent classes and ha+e additional, uni7ue properties andMor methods of their own. $+ents are actions that occur during the use of a computer program. $+ents are noticed by the computer and can result in a message being sent to a class or to a particular object to carry out an action. 1ometimes when messages are sent to objects additional information is needed to perform the task. This additional information is called the parameters.

Join me in lesson ! to learn how computers represent, store, and use data such as numbers, words, and more, in computer programs.

)*

También podría gustarte