Tài liệu Bài giảng Object-Oriented Software Engineering Practical Software Development using UML and Java - Chapter 2: Review of Object Orientation: Object-Oriented Software EngineeringPractical Software Development using UML and JavaChapter 2: Review of Object Orientation © Lethbridge/Laganière 20011Chapter 2: Review of Object Orientation2.1 What is Object Orientation?Procedural paradigm:Software is organized around the notion of procedures Procedural abstractionWorks as long as the data is simpleAdding data abstractions Groups together the pieces of data that describe some entity Helps reduce the system’s complexity. Such as Records and structuresObject oriented paradigm: Organizing procedural abstractions in the context of data abstractions© Lethbridge/Laganière 20012Chapter 2: Review of Object OrientationObject Oriented paradigmAn approach to the solution of problems in which all computations are performed in the context of objects. The objects are instances of classes, which:are data abstractionscontain procedural abstractions that operation on the objectsA running program can be seen as a collection of objects collaborating ...
45 trang |
Chia sẻ: honghanh66 | Lượt xem: 871 | Lượt tải: 0
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng Object-Oriented Software Engineering Practical Software Development using UML and Java - Chapter 2: Review of Object Orientation, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Object-Oriented Software EngineeringPractical Software Development using UML and JavaChapter 2: Review of Object Orientation © Lethbridge/Laganière 20011Chapter 2: Review of Object Orientation2.1 What is Object Orientation?Procedural paradigm:Software is organized around the notion of procedures Procedural abstractionWorks as long as the data is simpleAdding data abstractions Groups together the pieces of data that describe some entity Helps reduce the system’s complexity. Such as Records and structuresObject oriented paradigm: Organizing procedural abstractions in the context of data abstractions© Lethbridge/Laganière 20012Chapter 2: Review of Object OrientationObject Oriented paradigmAn approach to the solution of problems in which all computations are performed in the context of objects. The objects are instances of classes, which:are data abstractionscontain procedural abstractions that operation on the objectsA running program can be seen as a collection of objects collaborating to perform a given task © Lethbridge/Laganière 20013Chapter 2: Review of Object OrientationA View of the Two paradigms© Lethbridge/Laganière 20014Chapter 2: Review of Object Orientation2.2 Classes and ObjectsObjectA chunk of structured data in a running software system Has propertiesRepresent its stateHas behaviourHow it acts and reactsMay simulate the behaviour of an object in the real world© Lethbridge/Laganière 20015Chapter 2: Review of Object OrientationObjectsMargaret:date of birth: 1980/03/03position: TellerTransaction 487:amount: 200.00time: 2001/09/01 14:30Greg:date of birth: 1970/01/01address: 75 Object Dr.Mortgage Account 29865:balance: 198760.00opened: 2000/08/12property: 75 Object Dr.Instant Teller 876:location: Java Valley CafeSavings Account 12876:balance: 1976.32opened: 1997/03/03Jane:date of birth: 1955/02/02position: Manageraddress: 99 UML St.address: 150 C++ Rd.© Lethbridge/Laganière 20016Chapter 2: Review of Object OrientationClassesA class:Is a unit of abstraction in an object oriented (OO) program Represents similar objectsIts instancesIs a kind of software moduleDescribes its instances’ structure (properties)Contains methods to implement their behaviour© Lethbridge/Laganière 20017Chapter 2: Review of Object OrientationIs Something a Class or an Instance?Something should be a class if it could have instancesSomething should be an instance if it is clearly a single member of the set defined by a class FilmClass; instances are individual films.Reel of Film:Class; instances are physical reelsFilm reel with serial number SW19876Instance of ReelOfFilmScience FictionInstance of the class Genre.Science Fiction FilmClass; instances include ‘Star Wars’Showing of ‘Star Wars’ in the Phoenix Cinema at 7 p.m.:Instance of ShowingOfFilm© Lethbridge/Laganière 20018Chapter 2: Review of Object OrientationNaming classesUse capital lettersE.g. BankAccount not bankAccountUse singular nounsUse the right level of generalityE.g. Municipality, not CityMake sure the name has only one meaningE.g. ‘bus’ has several meanings© Lethbridge/Laganière 20019Chapter 2: Review of Object Orientation2.3 Instance VariablesVariables defined inside a class corresponding to data present in each instanceAttributesSimple dataE.g. name, dateOfBirthAssociationsRelationships to other important classesE.g. supervisor, coursesTakenMore on these in Chapter 5© Lethbridge/Laganière 200110Chapter 2: Review of Object OrientationVariables vs. ObjectsA variableRefers to an object May refer to different objects at different points in timeAn object can be referred to by several different variables at the same timeType of a variableDetermines what classes of objects it may contain © Lethbridge/Laganière 200111Chapter 2: Review of Object OrientationClass variables A class variable’s value is shared by all instances of a class. Also called a static variableIf one instance sets the value of a class variable, then all the other instances see the same changed value. Class variables are useful for:Default or ‘constant’ values (e.g. PI)Lookup tables and similar structuresCaution: do not over-use class variables © Lethbridge/Laganière 200112Chapter 2: Review of Object Orientation2.4 Methods, Operations and PolymorphismOperationA higher-level procedural abstraction that specifies a type of behaviourIndependent of any code which implements that behaviourE.g., calculating area (in general)© Lethbridge/Laganière 200113Chapter 2: Review of Object OrientationMethods, Operations and PolymorphismMethodA procedural abstraction used to implement the behaviour of a class.Several different classes can have methods with the same nameThey implement the same abstract operation in ways suitable to each class E.g, calculating area in a rectangle is done differently from in a circle© Lethbridge/Laganière 200114Chapter 2: Review of Object OrientationPolymorphismA property of object oriented software by which an abstract operation may be performed in different ways in different classes.Requires that there be multiple methods of the same nameThe choice of which one to execute depends on the object that is in a variableReduces the need for programmers to code many if-else or switch statements© Lethbridge/Laganière 200115Chapter 2: Review of Object Orientation2.5 Organizing Classes into Inheritance HierarchiesSuperclassesContain features common to a set of subclassesInheritance hierarchiesShow the relationships among superclasses and subclassesA triangle shows a generalizationInheritanceThe implicit possession by all subclasses of features defined in its superclasses© Lethbridge/Laganière 200116Chapter 2: Review of Object OrientationAn Example Inheritance HierarchyInheritanceThe implicit possession by all subclasses of features defined in its superclasses© Lethbridge/Laganière 200117Chapter 2: Review of Object OrientationThe Isa RuleAlways check generalizations to ensure they obey the isa rule“A checking account is an account”“A village is a municipality”Should ‘Province’ be a subclass of ‘Country’?No, it violates the isa rule“A province is a country” is invalid!© Lethbridge/Laganière 200118Chapter 2: Review of Object OrientationA possible inheritance hierarchy of mathematical objects © Lethbridge/Laganière 200119Chapter 2: Review of Object OrientationMake Sure all Inherited Features Make Sense in Subclasses© Lethbridge/Laganière 200120Chapter 2: Review of Object Orientation2.6 Inheritance, Polymorphism and Variables© Lethbridge/Laganière 200121Chapter 2: Review of Object OrientationSome Operations in the Shape Example© Lethbridge/Laganière 200122Chapter 2: Review of Object OrientationAbstract Classes and MethodsAn operation should be declared to exist at the highest class in the hierarchy where it makes senseThe operation may be abstract (lacking implementation) at that levelIf so, the class also must be abstractNo instances can be createdThe opposite of an abstract class is a concrete classIf a superclass has an abstract operation then its subclasses at some level must have a concrete method for the operationLeaf classes must have or inherit concrete methods for all operationsLeaf classes must be concrete© Lethbridge/Laganière 200123Chapter 2: Review of Object OrientationOverridingA method would be inherited, but a subclass contains a new version insteadFor restrictionE.g. scale(x,y) would not work in CircleFor extensionE.g. SavingsAccount might charge an extra fee following every debitFor optimizationE.g. The getPerimeterLength method in Circle is much simpler than the one in Ellipse© Lethbridge/Laganière 200124Chapter 2: Review of Object OrientationImmutable objectsInstance variables may only be set when an object is first created.None of the operations allow any changes to the instance variablesE.g. a scale method could only create a new object, not modify an existing one© Lethbridge/Laganière 200125Chapter 2: Review of Object OrientationHow a decision is made about which method to run1. If there is a concrete method for the operation in the current class, run that method.2. Otherwise, check in the immediate superclass to see if there is a method there; if so, run it.3. Repeat step 2, looking in successively higher superclasses until a concrete method is found and run.4. If no method is found, then there is an errorIn Java and C++ the program would not have compiled© Lethbridge/Laganière 200126Chapter 2: Review of Object OrientationDynamic bindingOccurs when decision about which method to run can only be made at run timeNeeded when:A variable is declared to have a superclass as its type, andThere is more than one possible polymorphic method that could be run among the type of the variable and its subclasses© Lethbridge/Laganière 200127Chapter 2: Review of Object Orientation2.7 Concepts that Define Object Orientation Necessary for a system or language to be OOIdentityEach object is distinct from each other object, and can be referred toTwo objects are distinct even if they have the same dataClassesThe code is organized using classes, each of which describes a set of objectsInheritanceThe mechanism where features in a hierarchy inherit from superclasses to subclassesPolymorphismThe mechanism by which several methods can have the same name and implement the same abstract operation. © Lethbridge/Laganière 200128Chapter 2: Review of Object OrientationOther Key ConceptsAbstractionObject -> something in the worldClass -> objectsSuperclass -> subclassesOperation -> methodsAttributes and associations -> instance variablesModularityCode can be constructed entirely of classesEncapsulationDetails can be hidden in classesThis gives rise to information hiding: Programmers do not need to know all the details of a class © Lethbridge/Laganière 200129Chapter 2: Review of Object OrientationThe Basics of JavaHistoryThe first object oriented programming language was Simula-67 designed to allow programmers to write simulation programs In the early 1980’s, Smalltalk was developed at Xerox PARC New syntax, large open-source library of reusable code, bytecode, platform independence, garbage collection.late 1980’s, C++ was developed by B. Stroustrup, Recognized the advantages of OO but also recognized that there were tremendous numbers of C programmersIn 1991, engineers at Sun Microsystems started a project to design a language that could be used in consumer ‘smart devices’: Oak When the Internet gained popularity, Sun saw an opportunity to exploit the technology. The new language, renamed Java, was formally presented in 1995 at the SunWorld ’95 conference.© Lethbridge/Laganière 200130Chapter 2: Review of Object OrientationJava documentationLooking up classes and methods is an essential skillLooking up unknown classes and methods will get you a long way towards understanding codeJava documentation can be automatically generated by a program called JavadocDocumentation is generated from the code and its commentsYou should format your comments as shown in some of the book’s examplesThese may include embeded html© Lethbridge/Laganière 200131Chapter 2: Review of Object OrientationOverview of JavaThe next few slides will remind you of several key Java featuresNot in the bookSee the book’s web site forA more detailed overview of JavaPointers to tutorials, books etc.© Lethbridge/Laganière 200132Chapter 2: Review of Object OrientationCharacters and StringsCharacter is a class representing Unicode charactersMore than a byte eachRepresent any world languagechar is a primitive data type containing a Unicode characterString is a class containing collections of characters+ is the operator used to concatenate strings© Lethbridge/Laganière 200133Chapter 2: Review of Object OrientationArrays and CollectionsArrays are of fixed size and lack methods to manipulate themVector is the most widely used class to hold a collection of other objectsMore powerful than arrays, but less efficientIterators are used to access members of VectorsEnumerations were formally used, but were more complexv = new Vector();Iterator i = v.iterator();while(i.hasNext()){ aMethod(v.next());}© Lethbridge/Laganière 200134Chapter 2: Review of Object OrientationCastingJava is very strict about typesIf a variable is declared to have the type X, you can only invoke operations on it that are defined in class X or its superclassesEven though an instance of a subclass of X may be actually stored in the variableIf you know an instance of a subclass is stored, then you can cast the variable to the subclassE.g. if I know a Vector contains instances of String, I can get the next element of its Iterator using: (String)iterator.next();© Lethbridge/Laganière 200135Chapter 2: Review of Object OrientationExceptionsAnything that can go wrong should result in the raising of an ExceptionException is a class with many subclasses for specific things that can go wrongUse a try - catch block to trap an exceptiontry{ // some code}catch (ArithmeticException e){ // code to handle division by zero}© Lethbridge/Laganière 200136Chapter 2: Review of Object OrientationInterfacesLike abstract classes, but cannot have executable statementsDefine a set of operations that make sense in several classesAbstract Data TypesA class can implement any number of interfacesIt must have concrete methods for the operationsYou can declare the type of a variable to be an interfaceThis is just like declaring the type to be an abstract classImportant interfaces in Java’s library includeRunnable, Collection, Iterator, Comparable, Cloneable© Lethbridge/Laganière 200137Chapter 2: Review of Object OrientationPackages and importingA package combines related classes into subsystemsAll the classes in a particular directoryClasses in different packages can have the same nameAlthough not recommendedImporting a package is done as follows:import finance.banking.accounts.*;© Lethbridge/Laganière 200138Chapter 2: Review of Object OrientationAccess controlApplies to methods and variablespublicAny class can accessprotectedOnly code in the package, or subclasses can access(blank)Only code in the package can accessprivateOnly code written in the class can accessInheritance still occurs!© Lethbridge/Laganière 200139Chapter 2: Review of Object OrientationThreads and concurrencyThread:Sequence of executing statements that can be running concurrently with other threadsTo create a thread in Java:1. Create a class implementing Runnable or extending Thread2. Implement the run method as a loop that does something for a period of time3. Create an instance of this class4. Invoke the start operation, which calls run© Lethbridge/Laganière 200140Chapter 2: Review of Object OrientationProgramming Style GuidelinesRemember that programs are for people to readAlways choose the simpler alternativeReject clever code that is hard to understandShorter code is not necessarily betterChoose good namesMake them highly descriptiveDo not worry about using long names© Lethbridge/Laganière 200141Chapter 2: Review of Object OrientationProgramming style Comment extensivelyComment whatever is non-obviousDo not comment the obviousComments should be 25-50% of the codeOrganize class elements consistentlyVariables, constructors, public methods then private methodsBe consistent regarding layout of code© Lethbridge/Laganière 200142Chapter 2: Review of Object OrientationProgramming style Avoid duplication of codeDo not ‘clone’ if possibleCreate a new method and call itCloning results in two copies that may both have bugsWhen one copy of the bug is fixed, the other may be forgotten© Lethbridge/Laganière 200143Chapter 2: Review of Object OrientationProgramming style ...Adhere to good object oriented principlesE.g. the ‘isa rule’Prefer private as opposed to publicDo not mix user interface code with non-user interface codeInteract with the user in separate classesThis makes non-UI classes more reusable© Lethbridge/Laganière 200144Chapter 2: Review of Object Orientation2.10 Difficulties and Risks in Object-Oriented ProgrammingLanguage evolution and deprecated features: Java can be less efficient than other languagesVM-basedDynamic bindingEfficiency can be a concern in some object oriented systems Java is evolving, so some features are ‘deprecated’ at every releaseBut the same thing is true of most other languages © Lethbridge/Laganière 200145Chapter 2: Review of Object Orientation
Các file đính kèm theo tài liệu này:
- ch02_327.ppt