mebigfatguy

legal_derby

May 18th, 2011
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.15 KB | None | 0 0
  1. select * from chapters where contents = 'Thinking in Java 4e—Sample Chapters
  2. Bruce Eckel
  3. Permission to use, copy, modify, and distribute this
  4. computer source code (Source Code) and its documentation
  5. without fee and without a written agreement for the
  6. purposes set forth below is hereby granted, provided that
  7. the above copyright notice, this paragraph and the
  8. following five numbered paragraphs appear in all copies.
  9. 1. Permission is granted to compile the Source Code and to
  10. include the compiled code, in executable format only, in
  11. personal and commercial software programs.
  12. 2. Permission is granted to use the Source Code without
  13. modification in classroom situations, including in
  14. presentation materials, provided that the book "Thinking in
  15. Java" is cited as the origin.
  16. 3. Permission to incorporate the Source Code into printed
  17. media may be obtained by contacting:
  18. MindView, Inc. 5343 Valle Vista La Mesa, California 91941
  19. 4. The Source Code and documentation are copyrighted by
  20. MindView, Inc. The Source code is provided without express
  21. or implied warranty of any kind, including any implied
  22. warranty of merchantability, fitness for a particular
  23. purpose or non-infringement. MindView, Inc. does not
  24. warrant that the operation of any program that includes the Source Code
  25. will be uninterrupted or error-free. MindView,
  26. Inc. makes no representation about the suitability of the
  27. Source Code or of any software that includes the Source
  28. Code for any purpose. The entire risk as to the quality
  29. and performance of any program that includes the Source
  30. Code is with the user of the Source Code. The user
  31. understands that the Source Code was developed for research and
  32. instructional purposes and is advised not to rely
  33. exclusively for any reason on the Source Code or any
  34. program that includes the Source Code. Should the Source
  35. Code or any resulting software prove defective, the user
  36. assumes the cost of all necessary servicing, repair, or
  37. correction.
  38. 5. IN NO EVENT SHALL MINDVIEW, INC., OR ITS PUBLISHER BE
  39. LIABLE TO ANY PARTY UNDER ANY LEGAL THEORY FOR DIRECT,
  40. INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
  41. INCLUDING LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF
  42. BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS, OR FOR
  43. PERSONAL INJURIES, ARISING OUT OF THE USE OF THIS SOURCE
  44. CODE AND ITS DOCUMENTATION, OR ARISING OUT OF THE INABILITY TO USE ANY
  45. RESULTING PROGRAM, EVEN IF MINDVIEW, INC., OR
  46. ITS PUBLISHER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  47. DAMAGE. MINDVIEW, INC. SPECIFICALLY DISCLAIMS ANY
  48. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  49. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  50. PURPOSE. THE SOURCE CODE AND DOCUMENTATION PROVIDED
  51. HEREUNDER IS ON AN "AS IS" BASIS, WITHOUT ANY ACCOMPANYING
  52. SERVICES FROM MINDVIEW, INC., AND MINDVIEW, INC. HAS NO
  53. Introduction
  54. 13
  55. OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
  56. ENHANCEMENTS, OR MODIFICATIONS.
  57. Please note that MindView, Inc. maintains a Web site which
  58. is the sole distribution point for electronic copies of the Source Code,
  59. http://www.MindView.net (and official mirror
  60. sites), where it is freely available under the terms stated above.
  61. If you think you\'ve found an error in the Source Code,
  62. please submit a correction using the feedback system that you will find at
  63. http://www.MindView.net.
  64. ///:~
  65. You may use the code in your projects and in the classroom (including your presentation
  66. materials) as long as the copyright notice that appears in each source file is retained.
  67. Coding standards
  68. In the text of this book, identifiers (methods, variables, and class names) are set in bold. Most
  69. keywords are also set in bold, except for those keywords that are used so much that the bolding
  70. can become tedious, such as “class.”
  71. I use a particular coding style for the examples in this book. As much as possible, this follows the
  72. style that Sun itself uses in virtually all of the code you will find at its site (see
  73. http://java.sun.com/docs/codeconv/index.html), and seems to be supported by most Java
  74. development environments. If you’ve read my other works, you’ll also notice that Sun’s coding
  75. style coincides with mine—this pleases me, although I had nothing (that I know of) to do with it.
  76. The subject of formatting style is good for hours of hot debate, so I’ll just say I’m not trying to
  77. dictate correct style via my examples; I have my own motivation for using the style that I do.
  78. Because Java is a free-form programming language, you can continue to use whatever style
  79. you’re comfortable with. One solution to the coding style issue is to use a tool like Jalopy
  80. (www.triemax.com), which assisted me in developing this book, to change formatting to that
  81. which suits you.
  82. The code files printed in the book are tested with an automated system, and should all work
  83. without compiler errors.
  84. This book focuses on and is tested with Java SE5/6. If you need to learn about earlier releases of
  85. the language that are not covered in this edition, the 1st through 3rd editions of the book are freely
  86. downloadable at www.MindView.net.
  87. Errors
  88. No matter how many tools a writer uses to detect errors, some always creep in and these often
  89. leap off the page for a fresh reader. If you discover anything you believe to be an error, please use
  90. the link you will find for this book at www.MindView.net to submit the error along with your
  91. suggested correction. Your help is appreciated.
  92. 14
  93. Thinking in Java 4e—Sample Chapters
  94. Bruce Eckel
  95. Introduction
  96. to Objects
  97. “We cut nature up, organize it into concepts, and ascribe significances as
  98. we do, largely because we are parties to an agreement that holds
  99. throughout our speech community and is codified in the patterns of our
  100. language ... we cannot talk at all except by subscribing to the
  101. organization and classification of data which the agreement decrees.”
  102. Benjamin Lee Whorf (1897-1941)
  103. The genesis of the computer revolution was in a machine. The genesis of our programming
  104. languages thus tends to look like that machine.
  105. But computers are not so much machines as they are mind amplification tools (“bicycles for the
  106. mind,” as Steve Jobs is fond of saying) and a different kind of expressive medium. As a result, the
  107. tools are beginning to look less like machines and more like parts of our minds, and also like
  108. other forms of expression such as writing, painting, sculpture, animation, and filmmaking.
  109. Object-oriented programming (OOP) is part of this movement toward using the computer as an
  110. expressive medium.
  111. This chapter will introduce you to the basic concepts of OOP, including an overview of
  112. development methods. This chapter, and this book, assumes that you have some programming
  113. experience, although not necessarily in C. If you think you need more preparation in
  114. programming before tackling this book, you should work through the Thinking in C multimedia
  115. seminar, downloadable from www.MindView.net.
  116. This chapter is background and supplementary material. Many people do not feel comfortable
  117. wading into object-oriented programming without understanding the big picture first. Thus,
  118. there are many concepts that are introduced here to give you a solid overview of OOP. However,
  119. other people may not get the big picture concepts until they’ve seen some of the mechanics first;
  120. these people may become bogged down and lost without some code to get their hands on. If
  121. you’re part of this latter group and are eager to get to the specifics of the language, feel free to
  122. jump past this chapter—skipping it at this point will not prevent you from writing programs or
  123. learning the language. However, you will want to come back here eventually to fill in your
  124. knowledge so you can understand why objects are important and how to design with them.
  125. The progress of abstraction
  126. All programming languages provide abstractions. It can be argued that the complexity of the
  127. problems you’re able to solve is directly related to the kind and quality of abstraction. By “kind” I
  128. mean, “What is it that you are abstracting?” Assembly language is a small abstraction of the
  129. underlying machine. Many so-called “imperative” languages that followed (such as FORTRAN,
  130. BASIC, and C) were abstractions of assembly language. These languages are big improvements
  131. over assembly language, but their primary abstraction still requires you to think in terms of the
  132. structure of the computer rather than the structure of the problem you are trying to solve. The
  133. programmer must establish the association between the machine model (in the “solution space,”
  134. 15
  135. which is the place where you’re implementing that solution, such as a computer) and the model
  136. of the problem that is actually being solved (in the “problem space,” which is the place where the
  137. problem exists, such as a business). The effort required to perform this mapping, and the fact
  138. that it is extrinsic to the programming language, produces programs that are difficult to write
  139. and expensive to maintain, and as a side effect created the entire “programming methods”
  140. industry.
  141. The alternative to modeling the machine is to model the problem you’re trying to solve. Early
  142. languages such as LISP and APL chose particular views of the world (“All problems are
  143. ultimately lists” or “All problems are algorithmic,” respectively). Prolog casts all problems into
  144. chains of decisions. Languages have been created for constraint-based programming and for
  145. programming exclusively by manipulating graphical symbols. (The latter proved to be too
  146. restrictive.) Each of these approaches may be a good solution to the particular class of problem
  147. they’re designed to solve, but when you step outside of that domain they become awkward.
  148. The object-oriented approach goes a step further by providing tools for the programmer to
  149. represent elements in the problem space. This representation is general enough that the
  150. programmer is not constrained to any particular type of problem. We refer to the elements in the
  151. problem space and their representations in the solution space as “objects.” (You will also need
  152. other objects that don’t have problem-space analogs.) The idea is that the program is allowed to
  153. adapt itself to the lingo of the problem by adding new types of objects, so when you read the code
  154. describing the solution, you’re reading words that also express the problem. This is a more
  155. flexible and powerful language abstraction than what we’ve had before.1 Thus, OOP allows you to
  156. describe the problem in terms of the problem, rather than in terms of the computer where the
  157. solution will run. There’s still a connection back to the computer: Each object looks quite a bit
  158. like a little computer—it has a state, and it has operations that you can ask it to perform.
  159. However, this doesn’t seem like such a bad analogy to objects in the real world—they all have
  160. characteristics and behaviors.
  161. Alan Kay summarized five basic characteristics of Smalltalk, the first successful object-oriented
  162. language and one of the languages upon which Java is based. These characteristics represent a
  163. pure approach to object-oriented programming:
  164. 1. Everything is an object. Think of an object as a fancy variable; it stores data, but
  165. you can “make requests” to that object, asking it to perform operations on itself. In
  166. theory, you can take any conceptual component in the problem you’re trying to solve
  167. (dogs, buildings, services, etc.) and represent it as an object in your program.
  168. 2. A program is a bunch of objects telling each other what to do by
  169. sending messages. To make a request of an object, you “send a message” to that
  170. object. More concretely, you can think of a message as a request to call a method that
  171. belongs to a particular object.
  172. 3. Each object has its own memory made up of other objects. Put
  173. another way, you create a new kind of object by making a package containing existing
  174. objects. Thus, you can build complexity into a program while hiding it behind the
  175. simplicity of objects.
  176. 1 Some language designers have decided that object-oriented programming by itself is not adequate to easily
  177. solve all programming problems, and advocate the combination of various approaches into multiparadigm
  178. programming languages. See Multiparadigm Programming in Leda by Timothy Budd (Addison-Wesley, 1995).
  179. 16
  180. Thinking in Java 4e—Sample Chapters
  181. Bruce Eckel
  182. 4. Every object has a type. Using the parlance, each object is an instance of a
  183. class, in which “class” is synonymous with “type.” The most important distinguishing
  184. characteristic of a class is “What messages can you send to it?”
  185. 5. All objects of a particular type can receive the same messages. This
  186. is actually a loaded statement, as you will see later. Because an object of type “circle” is
  187. also an object of type “shape,” a circle is guaranteed to accept shape messages. This
  188. means you can write code that talks to shapes and automatically handle anything that
  189. fits the description of a shape. This substitutability is one of the powerful concepts in
  190. OOP.
  191. Booch offers an even more succinct description of an object:
  192. An object has state, behavior and identity.
  193. This means that an object can have internal data (which gives it state), methods (to produce
  194. behavior), and each object can be uniquely distinguished from every other object—to put this in a
  195. concrete sense, each object has a unique address in memory.2
  196. An object has an interface
  197. Aristotle was probably the first to begin a careful study of the concept of type; he spoke of “the
  198. class of fishes and the class of birds.” The idea that all objects, while being unique, are also part
  199. of a class of objects that have characteristics and behaviors in common was used directly in the
  200. first object-oriented language, Simula-67, with its fundamental keyword class that introduces a
  201. new type into a program.
  202. Simula, as its name implies, was created for developing simulations such as the classic “bank
  203. teller problem.” In this, you have numerous tellers, customers, accounts, transactions, and units
  204. of money—a lot of “objects.” Objects that are identical except for their state during a program’s
  205. execution are grouped together into “classes of objects,” and that’s where the keyword class
  206. came from. Creating abstract data types (classes) is a fundamental concept in object-oriented
  207. programming. Abstract data types work almost exactly like built-in types: You can create
  208. variables of a type (called objects or instances in object-oriented parlance) and manipulate those
  209. variables (called sending messages or requests; you send a message and the object figures out
  210. what to do with it). The members (elements) of each class share some commonality: Every
  211. account has a balance, every teller can accept a deposit, etc. At the same time, each member has
  212. its own state: Each account has a different balance, each teller has a name. Thus, the tellers,
  213. customers, accounts, transactions, etc., can each be represented with a unique entity in the
  214. computer program. This entity is the object, and each object belongs to a particular class that
  215. defines its characteristics and behaviors.
  216. So, although what we really do in object-oriented programming is create new data types, virtually
  217. all object-oriented programming languages use the “class” keyword. When you see the word
  218. “type” think “class” and vice versa.3
  219. 2 This is actually a bit restrictive, since objects can conceivably exist in different machines and address spaces,
  220. and they can also be stored on disk. In these cases, the identity of the object must be determined by something
  221. other than memory address.
  222. 3 Some people make a distinction, stating that type determines the interface while class is a particular
  223. implementation of that interface.
  224. Introduction to Objects
  225. 17
  226. Since a class describes a set of objects that have identical characteristics (data elements) and
  227. behaviors (functionality), a class is really a data type because a floating point number, for
  228. example, also has a set of characteristics and behaviors. The difference is that a programmer
  229. defines a class to fit a problem rather than being forced to use an existing data type that was
  230. designed to represent a unit of storage in a machine. You extend the programming language by
  231. adding new data types specific to your needs. The programming system welcomes the new
  232. classes and gives them all the care and type checking that it gives to built-in types.
  233. The object-oriented approach is not limited to building simulations. Whether or not you agree
  234. that any program is a simulation of the system you’re designing, the use of OOP techniques can
  235. easily reduce a large set of problems to a simple solution.
  236. Once a class is established, you can make as many objects of that class as you like, and then
  237. manipulate those objects as if they are the elements that exist in the problem you are trying to
  238. solve. Indeed, one of the challenges of object-oriented programming is to create a one-to-one
  239. mapping between the elements in the problem space and objects in the solution space.
  240. But how do you get an object to do useful work for you? There needs to be a way to make a
  241. request of the object so that it will do something, such as complete a transaction, draw something
  242. on the screen, or turn on a switch. And each object can satisfy only certain requests. The requests
  243. you can make of an object are defined by its interface, and the type is what determines the
  244. interface. A simple example might be a representation of a light bulb:
  245. Type Name
  246. Interface
  247. Light
  248. on()
  249. off()
  250. brighten()
  251. dim()
  252. Light lt = new Light();
  253. lt.on();
  254. The interface determines the requests that you can make for a particular object. However, there
  255. must be code somewhere to satisfy that request. This, along with the hidden data, comprises the
  256. implementation. From a procedural programming standpoint, it’s not that complicated. A type
  257. has a method associated with each possible request, and when you make a particular request to
  258. an object, that method is called. This process is usually summarized by saying that you “send a
  259. message” (make a request) to an object, and the object figures out what to do with that message
  260. (it executes code).
  261. Here, the name of the type/class is Light, the name of this particular Light object is lt, and the
  262. requests that you can make of a Light object are to turn it on, turn it off, make it brighter, or
  263. make it dimmer. You create a Light object by defining a “reference” (lt) for that object and
  264. calling new to request a new object of that type. To send a message to the object, you state the
  265. name of the object and connect it to the message request with a period (dot). From the
  266. standpoint of the user of a predefined class, that’s pretty much all there is to programming with
  267. objects.
  268. The preceding diagram follows the format of the Unified Modeling Language (UML). Each class
  269. is represented by a box, with the type name in the top portion of the box, any data members that
  270. you care to describe in the middle portion of the box, and the methods (the functions that belong
  271. 18
  272. Thinking in Java 4e—Sample Chapters
  273. Bruce Eckel
  274. to this object, which receive any messages you send to that object) in the bottom portion of the
  275. box. Often, only the name of the class and the public methods are shown in UML design
  276. diagrams, so the middle portion is not shown, as in this case. If you’re interested only in the class
  277. name, then the bottom portion doesn’t need to be shown, either.
  278. An object provides services
  279. While you’re trying to develop or understand a program design, one of the best ways to think
  280. about objects is as “service providers.” Your program itself will provide services to the user, and it
  281. will accomplish this by using the services offered by other objects. Your goal is to produce (or
  282. even better, locate in existing code libraries) a set of objects that provide the ideal services to
  283. solve your problem.
  284. A way to start doing this is to ask, “If I could magically pull them out of a hat, what objects would
  285. solve my problem right away?” For example, suppose you are creating a bookkeeping program.
  286. You might imagine some objects that contain pre-defined bookkeeping input screens, another set
  287. of objects that perform bookkeeping calculations, and an object that handles printing of checks
  288. and invoices on all different kinds of printers. Maybe some of these objects already exist, and for
  289. the ones that don’t, what would they look like? What services would those objects provide, and
  290. what objects would they need to fulfill their obligations? If you keep doing this, you will
  291. eventually reach a point where you can say either, “That object seems simple enough to sit down
  292. and write” or “I’m sure that object must exist already.” This is a reasonable way to decompose a
  293. problem into a set of objects.
  294. Thinking of an object as a service provider has an additional benefit: It helps to improve the
  295. cohesiveness of the object. High cohesion is a fundamental quality of software design: It means
  296. that the various aspects of a software component (such as an object, although this could also
  297. apply to a method or a library of objects) “fit together” well. One problem people have when
  298. designing objects is cramming too much functionality into one object. For example, in your check
  299. printing module, you may decide you need an object that knows all about formatting and
  300. printing. You’ll probably discover that this is too much for one object, and that what you need is
  301. three or more objects. One object might be a catalog of all the possible check layouts, which can
  302. be queried for information about how to print a check. One object or set of objects can be a
  303. generic printing interface that knows all about different kinds of printers (but nothing about
  304. bookkeeping—this one is a candidate for buying rather than writing yourself). And a third object
  305. could use the services of the other two to accomplish the task. Thus, each object has a cohesive
  306. set of services it offers. In a good object-oriented design, each object does one thing well, but
  307. doesn’t try to do too much. This not only allows the discovery of objects that might be purchased
  308. (the printer interface object), but it also produces new objects that might be reused somewhere
  309. else (the catalog of check layouts).
  310. Treating objects as service providers is a great simplifying tool. This is useful not only during the
  311. design process, but also when someone else is trying to understand your code or reuse an object.
  312. If they can see the value of the object based on what service it provides, it makes it much easier to
  313. fit it into the design.
  314. The hidden implementation
  315. It is helpful to break up the playing field into class creators (those who create new data types)
  316. and client programmers4 (the class consumers who use the data types in their applications). The
  317. 4 I’m indebted to my friend Scott Meyers for this term.
  318. Introduction to Objects
  319. 19
  320. goal of the client programmer is to collect a toolbox full of classes to use for rapid application
  321. development. The goal of the class creator is to build a class that exposes only what’s necessary to
  322. the client programmer and keeps everything else hidden. Why? Because if it’s hidden, the client
  323. programmer can’t access it, which means that the class creator can change the hidden portion at
  324. will without worrying about the impact on anyone else. The hidden portion usually represents
  325. the tender insides of an object that could easily be corrupted by a careless or uninformed client
  326. programmer, so hiding the implementation reduces program bugs.
  327. In any relationship it’s important to have boundaries that are respected by all parties involved.
  328. When you create a library, you establish a relationship with the client programmer, who is also a
  329. programmer, but one who is putting together an application by using your library, possibly to
  330. build a bigger library. If all the members of a class are available to everyone, then the client
  331. programmer can do anything with that class and there’s no way to enforce rules. Even though
  332. you might really prefer that the client programmer not directly manipulate some of the members
  333. of your class, without access control there’s no way to prevent it. Everything’s naked to the world.
  334. So the first reason for access control is to keep client programmers’ hands off portions they
  335. shouldn’t touch—parts that are necessary for the internal operation of the data type but not part
  336. of the interface that users need in order to solve their particular problems. This is actually a
  337. service to client programmers because they can easily see what’s important to them and what
  338. they can ignore.
  339. The second reason for access control is to allow the library designer to change the internal
  340. workings of the class without worrying about how it will affect the client programmer. For
  341. example, you might implement a particular class in a simple fashion to ease development, and
  342. then later discover that you need to rewrite it in order to make it run faster. If the interface and
  343. implementation are clearly separated and protected, you can accomplish this easily.
  344. Java uses three explicit keywords to set the boundaries in a class: public, private, and
  345. protected. These access specifiers determine who can use the definitions that follow. public
  346. means the following element is available to everyone. The private keyword, on the other hand,
  347. means that no one can access that element except you, the creator of the type, inside methods of
  348. that type. private is a brick wall between you and the client programmer. Someone who tries to
  349. access a private member will get a compile-time error. The protected keyword acts like
  350. private, with the exception that an inheriting class has access to protected members, but not
  351. private members. Inheritance will be introduced shortly.
  352. Java also has a “default” access, which comes into play if you don’t use one of the aforementioned
  353. specifiers. This is usually called package access because classes can access the members of other
  354. classes in the same package (library component), but outside of the package those same
  355. members appear to be private.
  356. Reusing the implementation
  357. Once a class has been created and tested, it should (ideally) represent a useful unit of code. It
  358. turns out that this reusability is not nearly so easy to achieve as many would hope; it takes
  359. experience and insight to produce a reusable object design. But once you have such a design, it
  360. begs to be reused. Code reuse is one of the greatest advantages that object-oriented programming
  361. languages provide.
  362. The simplest way to reuse a class is to just use an object of that class directly, but you can also
  363. place an object of that class inside a new class. We call this “creating a member object.” Your new
  364. class can be made up of any number and type of other objects, in any combination that you need
  365. 20
  366. Thinking in Java 4e—Sample Chapters
  367. Bruce Eckel
  368. to achieve the functionality desired in your new class. Because you are composing a new class
  369. from existing classes, this concept is called composition (if the composition happens
  370. dynamically, it’s usually called aggregation). Composition is often referred to as a “has-a”
  371. relationship, as in “A car has an engine.”
  372. Car
  373. Engine
  374. (This UML diagram indicates composition with the filled diamond, which states there is one car.
  375. I will typically use a simpler form: just a line, without the diamond, to indicate an association.5)
  376. Composition comes with a great deal of flexibility. The member objects of your new class are
  377. typically private, making them inaccessible to the client programmers who are using the class.
  378. This allows you to change those members without disturbing existing client code. You can also
  379. change the member objects at run time, to dynamically change the behavior of your program.
  380. Inheritance, which is described next, does not have this flexibility since the compiler must place
  381. compile-time restrictions on classes created with inheritance.
  382. Because inheritance is so important in object-oriented programming, it is often highly
  383. emphasized, and the new programmer can get the idea that inheritance should be used
  384. everywhere. This can result in awkward and overly complicated designs. Instead, you should first
  385. look to composition when creating new classes, since it is simpler and more flexible. If you take
  386. this approach, your designs will be cleaner. Once you’ve had some experience, it will be
  387. reasonably obvious when you need inheritance.
  388. Inheritance
  389. By itself, the idea of an object is a convenient tool. It allows you to package data and functionality
  390. together by concept, so you can represent an appropriate problem-space idea rather than being
  391. forced to use the idioms of the underlying machine. These concepts are expressed as
  392. fundamental units in the programming language by using the class keyword.
  393. It seems a pity, however, to go to all the trouble to create a class and then be forced to create a
  394. brand new one that might have similar functionality. It’s nicer if we can take the existing class,
  395. clone it, and then make additions and modifications to the clone. This is effectively what you get
  396. with inheritance, with the exception that if the original class (called the base class or superclass
  397. or parent class) is changed, the modified “clone” (called the derived class or inherited class or
  398. subclass or child class) also reflects those changes.
  399. Base
  400. Derived
  401. 5 This is usually enough detail for most diagrams, and you don’t need to get specific about whether you’re using
  402. aggregation or composition.
  403. Introduction to Objects
  404. 21
  405. (The arrow in this UML diagram points from the derived class to the base class. As you will see,
  406. there is commonly more than one derived class.)
  407. A type does more than describe the constraints on a set of objects; it also has a relationship with
  408. other types. Two types can have characteristics and behaviors in common, but one type may
  409. contain more characteristics than another and may also handle more messages (or handle them
  410. differently). Inheritance expresses this similarity between types by using the concept of base
  411. types and derived types. A base type contains all of the characteristics and behaviors that are
  412. shared among the types derived from it. You create a base type to represent the core of your ideas
  413. about some objects in your system. From the base type, you derive other types to express the
  414. different ways that this core can be realized.
  415. For example, a trash-recycling machine sorts pieces of trash. The base type is “trash,” and each
  416. piece of trash has a weight, a value, and so on, and can be shredded, melted, or decomposed.
  417. From this, more specific types of trash are derived that may have additional characteristics (a
  418. bottle has a color) or behaviors (an aluminum can may be crushed, a steel can is magnetic). In
  419. addition, some behaviors may be different (the value of paper depends on its type and condition).
  420. Using inheritance, you can build a type hierarchy that expresses the problem you’re trying to
  421. solve in terms of its types.
  422. A second example is the classic “shape” example, perhaps used in a computer-aided design
  423. system or game simulation. The base type is “shape,” and each shape has a size, a color, a
  424. position, and so on. Each shape can be drawn, erased, moved, colored, etc. From this, specific
  425. types of shapes are derived (inherited)—circle, square, triangle, and so on—each of which may
  426. have additional characteristics and behaviors. Certain shapes can be flipped, for example. Some
  427. behaviors may be different, such as when you want to calculate the area of a shape. The type
  428. hierarchy embodies both the similarities and differences between the shapes.
  429. Shape
  430. draw()
  431. erase()
  432. move()
  433. getColor()
  434. setColor()
  435. Circle
  436. Square
  437. Triangle
  438. Casting the solution in the same terms as the problem is very useful because you don’t need a lot
  439. of intermediate models to get from a description of the problem to a description of the solution.
  440. With objects, the type hierarchy is the primary model, so you go directly from the description of
  441. the system in the real world to the description of the system in code. Indeed, one of the
  442. difficulties people have with object-oriented design is that it’s too simple to get from the
  443. beginning to the end. A mind trained to look for complex solutions can initially be stumped by
  444. this simplicity.
  445. 22';
Advertisement
Add Comment
Please, Sign In to add comment