CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-255 Storrs, CT 06269-2155 steve@engr.uconn.edu http://www.engr.uconn.edu/~steve (860) 486 - 4818 Copyright © 2000 by S. Demurjian, Storrs, CT. 1 Overview of Presentation CSE 2102 Abstraction and Modularization Concepts Quick Review Compare and Contrast Exploring Transitional Design Issues Revisiting Core Object-Oriented Concepts Encapsulation, Hiding, Inheritance, etc. Advanced Object-Oriented Concepts Polymorphism, Dispatching, Generics, etc. Exploring Concepts Summary and Discussion 2 Abstraction and Complexity CSE 2102 As Software has Become more Complex, it Requires more Software Engineers F. Brooks - Mythical Man Month - 1970s Work done in 2 months by 1 Software Engineer > Work done in 1 month by 2 SEs! “Adding Software Engineers to a Late Project will only Make it Later!” WHY? Interconnectedness: Interdependencies in Code Individual Portions can’t be Written in Isolation Information Exchange Needed Between SEs Complexity Historically Controlled by Abstracting Away Less Important Details 3 CSE 2102 Abstraction 4 CSE 2102 Encapsulation 5 History of Abstraction Procedures and Modules CSE 2102 Procedures The “First” Abstraction Mechanism Repeated Execution of Same Code without Duplication Inefficient at Information Hiding Modules: Managing Name Spaces Public: Portion Accessible Outside Module Private: Portion Accessible Inside Module Users can Only “See” Information Needed to Utilize Module SE can Only “See” Information Needed to Code Module Supports Information Hiding 6 CSE 2102 Module 7 Abstract Data Types (ADTs) CSE 2102 Proposed by B. Liskov (MIT) for CLU in 1975 ADTs Promote Application Development From Perspective of Information and its Usage ADT Design Process: Identify “Kinds” or “Types” of Information Encapsulate Information and Provide a Public Interface of Methods Hide Information and Method Code in the Private Implementation ADTs Correspond to User-Defined Data Types Analogous to Integer Data Type and +, -, *, etc. 8 Abstract Data Types (ADTs) CSE 2102 Consider the following Example Stack ADT: Public Interface Private Implementation Head: Int; ST: Array[100] of Int; User PUSH POP TOP EMPTY Designer Push(X Int) … End; Int Pop() … End; PUSH 5 10 15 20 20 15 10 5 ST 5 TOP 20 15 10 5 9 ADT Design Guidelines CSE 2102 Separation of Concerns and Modularity Problem Decomposable into Components Abstraction and Representation Independence Hiding Implementation of Components Changing without Impacting External View Incrementality and Anticipation of Change Components are Changed, Added, Refined, etc., as Needed to Support Evolving Requirements Cohesion: Well-Defined Component Performs a Single Task or has a Single Objective Coupling: Component Interactions are Known and Minimal 10 Object-Oriented Paradigm CSE 2102 Object-Oriented Decomposition Decompose Problem into Agents which Perform Operations Emphasize Agents that Cause Actions Agents Comprised of Two Parts Hidden Implementation: Data and Operations only Available to Agent Public Interface: Operations Available to Clients of Agent An Agent Can Only be Modified by Operations Defined in either the Hidden Implementation or Public Interface 11 Core Object-Oriented Concepts CSE 2102 Class The Type of an Agent Describes the Behavior Object The Instance of a Class Represents Actual Data Manipulated by Agents Maintains the State of Object Method Operation Defined on a Class Operates on ALL Instances of the Class Message Indicates that an Object’s Method Invoked 12 CSE 2102 What is a Class? 13 What is a Class ? CSE 2102 occurrences roles organizational units things places structures external entities class name attributes: operations: •A class is a generalized description of a collection of similar objects. •Object is an instance of a class. •Class exports: -Operations used to manipulate instances -May export attributes. 14 CSE 2102 Two Representations of a Class 15 Operations (or Methods or Services) Defined on a Class CSE 2102 An executable procedure that is a part of a class and operates on the data attributes defined as part of the class A method operates on all instances of a class A method is invoked via message passing 16 CSE 2102 Messages Messages - the means by which objects invoke each other’s methods. 17 An Example Employee Class CSE 2102 Class Employee { //Hidden Implementation Private: //Instance Vars char[30] name; float salary; //Public Interface Public: void print_name(); void print_salary(); void update_salary(float i); Employee(char *n, float s); } What’s Output of Main()? Steve 100.0 Lois 130.0 Main() { //Declare Objects Employee emp1(Steve,100.0); Employee emp2(Lois, 120.0); //Pass Messages //Invoke Methods emp1.print_name(); emp1.print_salary(); emp2.update_salary(10); emp2.print_name(); emp2.print_salary(); } Conclusion: Each Object (emp1,emp2) has Own Independent State that is Accessible via Shared Public Interface of Class 18 Modules vs. ADTs/Classes CSE 2102 Module Describes Both State and Behavior Module Employee Includes Instance Variables, Operations, and Program Variables Single Instance Shared by All Users Class Describes Only the Behavior Class Employee Omits Program Variables Multiple Independent Instances Share Same Class Declaration but have Separate States Key Difference: Dynamic Nature of Classes Allows Instances to be Created as Needed 19 Object-Oriented Concepts CSE 2102 Background and Motivation Transitional Design & Silver Bullet (Brooks) Law of Demeter/Responsibility-Driven Design Object-Oriented Design Issues The High-Tech Supermarket System (HTSS) Choosing Objects and Classes Inheritance and Overloading Polymorphism/Dynamic Binding Generic: A Type Parameterizable Class “Software Design,” and “Object-Oriented Design”, Chapter 108 and 109, The Computer Science & Engineering Handbook, Tucker (ed.), CRC Press, 2nd Edition, 2002. 20 Concepts of Transitional Design CSE 2102 What Does Customer Want? What Does Designer Need? Comprehensive Object-Oriented Design Must: Characterize Classes and Inheritance Understand Relationships Among Classes Design for Today and Tomorrow Talk to Customer! KEY: Define the Problem and Understand its Domain and Scope 21 Transitional Design - Practice CSE 2102 Focus on Encapsulation, Hiding, and Inheritance Emphasize a Behavioral Perspective: What's Encapsulated/Hidden? Actions/Responsibilities are Key! Interdependencies are Critical! While Encapsulation and Hiding Typically Imply an Independence Among “Classes” (other than Inheritance), Our Claim is that Such a View is Artificial and Unrealistic! Represent “World” as it Occurs, Not as we Would Like it to Occur! 22 Thoughts From Fred Brooks CSE 2102 “No Silver Bullet”, IEEE Computer, Apr. 1987 Common Motivation: “Hardest Part is Deciding What to Build” “Most Important Functions is Iterative Extraction and Refinement of the Product Requirements” “Impossible - Completeness, Preciseness, Correctness” Focus on the Identification, Cultivation, Recognition and Reward of “Great Designers” “Biting the Silver Bullet”, D. Harel, IEEE Computer, Jan. 1992 23 Law of Demeter CSE 2102 (Leiberherr, Northeastern University) Stress Encapsulation by Reducing Interdependencies Between Classes (Objects) High Cohesion and No Coupling A Class Cannot Directly Manipulate (via Method) Internal Representation of Another Class Classes Developed and Analyzed Independently Focus on Method Access and Message Sending Only Objects in Parameter List of Methods Instance Variables of Class but NOT Superclasses Global and Temporary Variables 24 Responsibility-Driven Design CSE 2102 (Wirfs-Brock & Wilkerson, OOPSLA89) Approach Emphasizes Responsibilities: “What actions is this object responsible for?” “What information does this object share?” Three Perspective Client Model: External Clients Subclass Clients Self Client Focus on Actions and Behavior Interactions Inevitable! Key: Define Required Interactions 25 Objects vs. ADTs CSE 2102 Objects Extend ADTs as follows: Message Passing: Object Activation by a Request (Method Call) to Perform an Action Inheritance: Sharing of Code Among Objects Polymorphism: Shared Code Behaves Differently Based on Object and Context ADT/OO Benefits: Support Creation of Reusable Software Components Creation and Testing in Isolation! SEs View Problem at Higher-Level of Abstraction 26 Choosing Objects and Classes CSE 2102 The ‘First’ and Most ‘Often’ Concern for Newcomers to OO Concepts Typical Answers: High Cohesion, Low Coupling, Encapsulation Law of Demeter, Responsibility-Driven Design Comes with Experience and Time Better Answer: Choosing Objects/Classes Not a First Step Can't Jump to High-Level/Detailed Design Choice Guided by Specification - Contains Intent and Requirements DFDs, ERs, Interfaces, User Interactions, etc. 27 Choosing Objects and Classes CSE 2102 Employee class Private data: Name Address SSN Salary Public interface: Create_employee() Give_Raise_Amount(Amount) Change_Address(New_Addr) Based on an information perspective, focusing on the idea that to track Employees a set of standard data and operations are needed 28 Choosing Objects and Classes CSE 2102 ATM_log class: Private data: Acct_name PIN_number Public interface: Check_database(Name) Verify_PIN(PIN) Log_on_Actions(Name,PIN) Reject() Embodies the functions that take place to authenticate an individual to an ATM session Even with a functional view, information is needed to capture user input for verifying status 29 Choosing Objects and Classes CSE 2102 ATM_User: Private data: Action Balance WD_Amt Public interface: Log_on_Steps() Acct_WithD() Check_Balance(Number) Deposit_Check() User interface by capturing the different interactions between the ATM and the user 30 Choosing Objects and Classes CSE 2102 Start from the problem specification Objects include physical entities as well as concepts such as seating arrangement, payment schedule Not all classes maybe explicit in the problem statement and may rely on domain knowledge for identification Objects frequently correspond to nouns in the statement 31 Choosing Objects and Classes CSE 2102 An appointments system that will allow telephone callers to book an appointment with a doctor. The caller will specify the day and the time when he wishes to be seen by a doctor. Tentative classes could be: Appointment, system, telephone, caller, doctor, day, time Patient - from domain knowledge Caller and patient express the same information but one is more meaningful in the context. 32 Choosing Objects and Classes CSE 2102 Identifying operations: Attributes Events in the scenarios Real-world behavior Attributes: Need operations to set and read attributes Events in the scenarios: A scenario consists of interactions (events exchanged) that have to take place among the objects to achieve the functionality. Identify common and rare scenarios. Events passed to and from the objects implies operation on the object or message from it. 33 Choosing Objects and Classes CSE 2102 Real world can also suggest the operations needed to support a class : Useful in broadening the scope of the class beyond its immediate application. Operations should not overlap each other: Use simple operations to create more complex activities e.g an edit operation could consist of copy, delete and insert. Number of operations that have access to the data should be reduced to a minimum. Operations may refer to verbs in the problem description 34 CSE 2102 Inheritance 35 Inheritance – Example #1 CSE 2102 A vehicle registration system maintains registration information about all types of vehicles owned by individuals. These include the ones that run on land, sail in water and fly in the air. The vehicles that run on the land include cars and trucks, the vehicles that sail in the water include sailboats, ships, motorboats and yatchs, and the vehicles that fly in the air include airplane and helicopters. Construct an inheritance hierarchy for the vehicle registration system. 36 CSE 2102 Inheritance – Example #2 Consider a shipping cost calculation system that calculates shipping costs for a batch of packages. Packages can be shipped via three methods, namely, US Mail, FedEx or UPS. For each of these three methods, the customer has a choice of using either standard or priority shipping. The calculation of the shipping costs differs depending on which method is used. Construct an inheritance hierarchy for the shipping cost system. 37 Choosing Objects for BlackJack CSE 2102 Consider ‘Naïve’Abstraction: Deck +---------+ | Shuffle | | Deal | | Hit | | ... | +---------+ Hand +-------+ | Play | | Hit | | Stand | | ... | +-------+ Game +-------------------+ | +----+ +----+ | | |Hand| |Hand| ... | | +----+ +----+ | | Operations? | +-------------------+ What's Been Ignored? Multiple Decks of Cards? Modeling of Deck - Suits/Cards? Strategy for House? Moral: Objects/Classes are Not a Panacea for Comprehensive, Up-Front, Problem Exploration via a Detailed Specification 38 Object-Oriented Design Issues CSE 2102 The High-Tech Supermarket System (HTSS) Description of Capabilities Modules and ADTs for HTSS Categories of Classes Common Design Flaws 39 CSE 2102 High-Tech Supermarket System (HTSS) Automate the Functions and Actions Cashiers and Inventory Updates User Friendly Grocery Item Locator Fast-Track Deli Orderer Inventory Control User System Interfaces Cash Register/UPC Scanner GUI for Inventory Control Shopper Interfaces Locator and Orderer Deli Interface for Deli Workers We’ll Introduce and Utilize Throughout Course 40 The HTSS Software Architecture CSE 2102 IL IL IL SDO EDO SDO EDO Payment CR CR CR CR IL: CR: IC: DO: Item Locator Cash Register Invent. Control Deli Orderer for Shopper/Employee Item IC Order IC Non-Local Client Int. CreditCardDB Inventory Control ItemDB Global Server ItemDB Local Server ATM-BanKDB OrderDB SupplierDB 41 Programming with Modules CSE 2102 Modular Design and Development Contains: Identification of Major System Tasks Each Task Contains Dedicated Set of Data and Imports Data/Functions from Other Modules Each Task Contains a Set of Procedures and/or Functions to Accomplish Task Each Task Exports Subset of Information, Procedures, and/or Functions to “World” Versatility in Design Approach: Functional Modules for: Cashier, Scanner, Locator, Orderer, Inventory Controller, etc. Informational Modules for Item, DeliItem, Receipt, Credit/Check. 42 CSE 2102 Modules in HTSS MODULE Cashier; IMPORT Get_Item(UPC), Get_Credit_Info(AcctNum), Get_Deli_Item(UPC), ...; EXPORT Display_SubTot(), Display_Total(), Generate_Receipt(), ...; MODULE Scanner; ... END Scanner; {code for internal data and for procedures and functions} END Cashier; MODULE Orderer; ... END Orderer; MODULE Items; IMPORT {various I/O routines}; EXPORT Get_Item(UPC), New_Item(UPC, Name, ...), Modify_Item(UPC, Integer), Delete_Item(UPC), ...; anItem = RECORD UPC : INTEGER; NAME: STRING; SIZE: REAL; ... END; END Items; MODULE DeliItems; ... END DeliItems; MODULE Locator; ... END Locator; MODULE CreditCheck; ... END CreditCheck; 43 Advantages/Drawbacks of Modules CSE 2102 Import/Export: Concept Similar to Public Interface Promotes Controlled Sharing Provides Hiding Facilitates Concurrent Engineering Strong Parallels to ADTs No Concept of “Instances” But, Still Emphasizes Functional Solution Like OO/ADT, Supports Representation Independence 44 Programming with ADTs CSE 2102 ADTs Promote Applications Development From Perspective of Information and Its Usage ADT Design Process and Steps: Identify Major “Kinds/Types” of Information Describe Purpose Each Kind or Type Encapsulate Information Define and Characterize Methods Process Iterates/Cycles from Bottom Up Focus on Lowest Level of Info. - Build ADTs Next Level of ADTs Use Lowest Level Next Level Combines most Recent Levels Repeat to Achieve Desired System level 45 CSE 2102 ADTs in HTSS ADT Item; PRIVATE DATA: SET OF Item(s), Each Item Contains: UPC, Name, WCost, RCost, OnShelf, InStock, Location, ROLimit; PTR TO Current_Item; PUBLIC OPS: Create_New_Item(UPC, ...) : RETURN Status; Get_Item_NameCost(UPC) : RETURNS (STRING, REAL); Modify_Inventory(UPC, Delta) ; Get_InStock_Amt(UPC) : RETURN INTEGER; Get_OnShelf_Amt(UPC) : RETURN INTEGER; Check_If_On_Shelf(UPC): RETURN BOOLEAN; Time_To_Reorder(UPC): RETURN BOOLEAN; Get_Item_Profit(UPC): RETURN REAL; ... {notes: - OPS span the entire application - not limited to a single, functional component} END Item; ADT DeliItem; ADT CustomerInfo; PRIVATE DATA: SET OF (Item, Weight, ... CostLb, Increm); END CustomerInfo; ... END DeliItem; 46 CSE 2102 ADTs in HTSS ADT Process_Order; {middle-level ADT} PRIVATE DATA: {local variables to process an order} PUBLIC OPS : {what do you think are appropriate?} {this ADT uses the ADT/PUBLIC OPS from Item, Deli_Item, Receipt, Coupons, and Customer_Info to process and total an Order.} END Process_Order; ADT Sales_Info; {middle-level ADT} PRIVATE DATA: {local variables to collate sales information} PUBLIC OPS : {what do you think are appropriate?} {this ADT uses the ADT/PUBLIC OPS from Receipt so that the sales information for the store can be maintained.} END Sales_Info; ADT Cashier; {high-level ADT} {this ADT uses the ADT/PUBLIC OPS from the middle-level ADTs (Process_Order, Sales_Info, etc.).) END Cashier; 47 Advantages/Drawbacks of ADTs CSE 2102 Advantages: Abstraction is Promoted and Achieved Concurrent Engineering is Feasible Reuse and Evolution are Attainable Emphasizes Static System Behavior Drawbacks: Without Inheritance, Redundancies Likely Dynamic System Behavior Still Difficult Associations Between ADTs Difficult Only Inclusion Association Supported Do Drawbacks Outweigh Advantages? 48 Responsibility-Driven Design CSE 2102 (Wirfs-Brock & Wilkerson, OOPSLA89) Approach Emphasizes Responsibilities: “What actions is this object responsible for?” “What information does this object share?” “What objects does this object collaborate with?” Focus on Actions and Behavior Interactions Inevitable! Key: Define Required Interactions 49 CRC Cards Class, Responsibility, Collaborators CSE 2102 Index Cards - Each Card Defines a Class Front of Each CRC Card: Class - Meaningful Chunk Responsibilities Well-Chosen Prose Descriptions of Capabilities What Actions Does a Class Perform? Design Version of Method Collaborators Interactions with Other Classes Which Classes does Class Interact with? Back of Each CRC Card: Data - Hidden from Users 50 CSE 2102 A CRC Card for HTSS Item: A Product Sold in a Supermarket. Create a New Item Return an Item's UPC Return an Item's Name Return the Quantity of an Item Return an Item's Reorder Amount Check the Reorder Status of Item Display all Info. on an Item Display an Item's Name and Price Display an Item's Inventory Data Update an Item's Price ItemDB Hidden Data: Name: String; UPC: String; Rcost, Wcost: Real; Quantity, ReorderLevel: Integer; etc... 51 CSE 2102 Another CRC Card for HTSS ItemDB: All Item’s in Supermarket - repository. Insert a New Item Delete an Existing Item Find/Display Item Based on UPC Find/Display Item Based on Name Find/Display Item Based on Qty Find/Display Item Based on Reorder Print All Items Find an Item in Database by UPC Find an Item in Database by Name Find the First Item Find the Next Item InvControl Item Hidden Data: AllItems: Array[1..MaxItem] of Item; CurrItem, LastItem: Integer Index; etc... 52 Flight Management Example CSE 2102 Capabilities Include: User Requests a Number of Seats on a Certain Flight System Grants Requests if Possible and Issues Tickets, or Denies Request User Requests a Cancellation of a Number of Seats on a Certain Flight System Grants Cancellation and Issues Refund For Simplicity, Ignore Overbooking and Attempts to Cancel Unbooked Flights Using this Terse Description - Develop a Solution We’ll Explore Alternatives Shortly 53 CSE 2102 CRC Cards for Flight Example One Solution Agent: Handles Ticketing for Passengers. Display Transaction Menu Wait for Transaction Call Apropos Trans. Manager Reserve Cancel Reserve: Actions for Making Reservation. Ask Schedule if Seats Available Ask Flight to Reserve Seats Ask Issue to Generate Tickets Flight Schedule Issue Cancel: Actions for Canceling Reservation. Ask Flight to Cancel Seats Ask Issue to Generate Refund Flight Issue 54 CRC Cards for Flight Example One Solution CSE 2102 Schedule: Flight Interactions/Ticketing. Get Ask Ask Ask No. Seats Flight if Flight to Flight to and Flight No. No. Seats Available Reserve Seats Cancel Seats Flight Flight: Tracks Seat Info. for Flights. Compare No. Seats with No. Available Remove Seats from Free List Return Seat No. to Schedule Add Cancelled Seat No. to Free List Issue: Generate Ticket or Cancellation. Issue Ticket Issue Refund Check 55 CRC Cards for Flight Example Critiquing First Solution CSE 2102 Design Represents User Perspective Highlight Interactions via Collaborators Cancel Agent Reserve Commonalties? Differences? Couplings? Schedule Flight Issue 56 CSE 2102 Another Solution Combine Reserve, Cancel, and Issue Agent: Handles Ticketing for Passengers. Display Transaction Menu Wait for Transaction Call Apropos Trans. Manager Reserve Cancel Reservations: Making/Canceling Reservations. Ask Schedule if Seats Available Ask Flight to Reserve Seats Ask Issue to Generate Tickets Ask Flight to Cancel Seats Ask Issue to Generate Refund Issue Ticket Issue Refund Check Flight Schedule Issue 57 Yet Another Solution Combine Schedule and Flight CSE 2102 Schedule: Flight Interactions/Ticketing. Get No. Seats and Flight No. Ask Flight if No. Seats Available Ask Flight to Reserve Seats Ask Flight to Cancel Seats Compare No. Seats with No. Available Remove Seats from Free List Return Seat No. to Schedule Add Cancelled Seat No. to Free List Flight What was Problem with Original Design? What has Occurred in Redesign? Structuring Solution from Perspective of Arrival/Departure of Flights Would Likely Yield Different Set of Classes!! 58 Categories of Classes CSE 2102 Data Managers - Maintain Data/State Information Contains Functionality for Application class Item { private: // Private Data int UPC; char* Name; int InStock, OnShelf, ROLimit; float RetailCost; public: // Public Methods Item(int code, char* str, int st1, int st2, int st3, float cost); void CreateNewItem(); int GetUPC(); char* GetName(); int GetQuantity(); int CheckReorderStatus(); void PrintItem(); void UpdatePrice(float new_value); }; 59 Categories of Classes CSE 2102 Data Sinks/Data Sources - Produce/Process Data Generated on Demand or Maintained class ItemDB {private: int Num_Items; int Curr_Item; Item* AllItems[Max_Items]; int int int int public: void void void void void }; FindFirstItem(); FindNextItem(); FindItemUPC(int code); FindItemName(char* name); ItemDB(); // Constructor InsertNewItem(Item* new_one); DeleteExistingItem(int code); FindDisplayItemUPC(int code); FindDisplayItemName(char* name); PrintAllItems(); 60 Categories of Classes CSE 2102 Data Manager Class Item Class Contains the State of a Single Object Item I1, I2, I3; Data Source/Sink Class ItemDB is a Collection or Set of Items Item ItemDB[100]; I1 “milk” I2 “peas” I3 “soda” ItemDB 61 Categories of Classes CSE 2102 View/Observer - Provide an Interface for User Often Collects Information via Public Interface of Multiple Classes InvControlGUI Utilizes Item, ItemDB, etc. class InvControlGUI { private: int Curr_Option; // Current menu option public: InvControl(); // Constructor void PrintMenuSetOption(); void ActivateController(); void EnterNewItem(); void RemoveExistingItem(); void FindItem(); void InvSearchQuantity(); void InvSearchReorder(); void GenerateAnOrder(); }; 62 Categories of Classes CSE 2102 Facilitator/Helper - Used to Support Complex Tasks E.g., GUI Libs, Strings, I/O Handler, etc. For HTSS, Facilitator/Helpers as Follows: GUI Classes to Display Windows, Menu Options, Dialog Boxes, etc., for HTSS GUIs Linked List or Collection Classes to Allow Data to be Stored in ItemDB Is UPC Scanner a Facilitator/Helper Class? 63 Methodological Issues for OO Design CSE 2102 Design Grows Over Time Begin by Identifying Classes Vital to Application Simulate Scenarios of Expected Operation Identify New Classes Assign/Revise Methods to Classes Classes Demonstrate Flow of Control Experimental Approach to Design - Advantages Group Approach to Problem Solving Communication between Team Members Alternative Design Evaluation Completeness of Design High-Level yet Means for Details 64 CSE 2102 Early Stage of OO Design Class A Class B Class D Class C Class E Class B Class A Class C Class F 65 Methodological Issues CSE 2102 From First/Initial Attempts, Classes are Evolved Towards “Complete” Design Addition of New Classes Expand with New Methods Fine Tune Relationships Add/Refine “Hidden” Data Combine “Small/Similar” Classes Split “Large/Poorly Abstracted” Classes As Time Goes on, Include Inheritance: One Class is a Specialization of Another Class Aggregation: One Class is a Component of Another Class 66 CSE 2102 Later Stage of OO Design Class D Class E Int X, Y; Char Z; Real M, N; String S; Class B Method Method Method Method B1 B2 B3 B4 Class A Class C Method A1 Method A2 Method A3 Method C1 Method C2 Class F 67 Common Design Flaws CSE 2102 Classes that Directly Modify the Private Data of Other Classes Provide Operations in Public Interface Only Change via Operations Asking Class to Change Itself Recall Item from HTSS class Item { private: // Private Data float RetailCost; public: // Public Methods void UpdatePrice(float new_value); }; Only Change RetailCost via UpdatePrice() Do not Access RetailCost Directly from Cashier 68 Common Design Flaws CSE 2102 Too Much Functionality in One Class Class Grows Over Time - Not Cohesive Split a Class into Two or More Classes class Item { protected: // Attributes as given in earlier examples public: // Two constructors for versatility virtual virtual virtual virtual virtual virtual int char* int int int int float float GetUPC(); GetName(); GetInstockAmt(); GetOnShelfAmt(); GetQuantity(); GetReorderAmt(); GetRetailPrice(); GetWholeSaleCost(); void void void void void void UpdateName(char* item_name); UpdateInstockAmt(int stock_amt); UpdateOnShelfAmt(int shelf_amt); UpdateReorderAmt(int reord_amt); UpdateRetailPrice(float price); UpdateWholeSaleCost(float wholesale); void void void void void char* void void void void void void void void CreateNewItem(); PrintItem(); PrintPerish(); UpdateItemMenu(); UpdateItem(int portion); ReturnType(); PrintUPCName(); PrintNamePrice(); PrintInventory(); PrintProfitInfo(); PrintUPC(); PrintName(); PrintInstockAmt(); PrintOnShelfAmt(); } 69 Common Design Flaws CSE 2102 A Class that Lacks Functionality Class Included at Early Design Stage Merge Two or More Classes Impact on Inheritance Hierarchies? Classes that Have Unused Functionality Eliminate Unused Functions and Reevaluate Their Necessity Classes that Duplicate Functionality Combine with Existing Class Add Non-Duplicate Functionality 70 Advanced Object-Oriented Concepts CSE 2102 Inheritance Controlled Sharing of Between Classes Generalization and Specialization Treat Instances of Different Classes in Uniform Fashion - Leading to … Polymorphism/Dynamic Binding Run-Time Choice of the Method to be Invoked Based on the Type of the Calling Instance Message Passed is Type Dependent Generic: A Type Parameterizable Class Stack has Parameter for Type of Element Creation of Program Variable Binds Stack Data and Methods to Specific Type of Element Stack(Real), Stack(Int), Stack(Employee) 71 Motivating Inheritance Concepts CSE 2102 Consider a University Application Four Classes Have Been Identified Faculty Name SSN Rank Dept Yrs Dean Name SSN School Dept Yrs UnderGrad Name SSN Dorm Year GPA Grad Name SSN Dorm Program Degree GPA To Successfully Utilize Inheritance Distinguish Differences (Specialization) Identify Commonalties (Generalization) 72 Motivating Inheritance CSE 2102 One Solution: Person Name SSN Faculty:Person Rank Dept Yrs UnderGrad:Person Dorm Year GPA Dean:Person School Dept Yrs Grad:Person Dorm Program Degree GPA Pictorially: Person Faculty Dean UnderGrad Grad Is this Solution Adequate? 73 Motivating Inheritance CSE 2102 A Better Solution: Person Name SSN Employee Dept Yrs Faculty Rank Dean School Student Dorm GPA UnderGrad Year Grad Program Degree Solution Utilizes Single Inheritance Exactly One Parent for Each Class Are we Done? 74 Motivating Inheritance CSE 2102 Revising Example: Person Name SSN Employee Dept Yrs Faculty Rank Dean School Student Dorm GPA UnderGrad Year Grad Program Degree Superclass, Supertype, Parent, Base Class Subclass, Subtype, Child, Derived Class Descendants, Ancestors, Siblings 75 Defining Inheritance CSE 2102 Subclass Acquires Information and/or Operations of a Superclass Inheritance is a Transitive Operation Behavior and Information of a Subclass is a Superset of its Ancestors Subclass is More Refined than Superclass - its Specialized Superclass contains Common Characteristics of its Subclasses - its Generalized 76 Defining Inheritance CSE 2102 Inheritance is Utilized when Two or More Classes are Functionally and/or Informationally Related In University Example, Common Data Basis of Inheritance Decision Other Bases for Inheritance could be: Common Methods Common Data and Methods Reuse Occurs from both Informational and Functional Perspective Information - No Replicated Variables Function - No Replicated Code 77 The Role of Inheritance CSE 2102 Develop Inheritance Hierarchies that are Extensible Reusable Evolvable In Budd, Chapter 7, Excellent Discussion on Utilization of Inheritance: How Benefits of Inheritance: Why Impact of Inheritance: Cost We’ll Review this Material 78 Specialization and Generalization Inheritance CSE 2102 Specialization Most Common form of Inheritance to Refine the Behavior of the SuperClass Differences are Pushed Down Hierarchy Allows Designers to Customize Classes Generalization Inverse of Specialization Commonalities of Multiple Classes are Abstracted out to Form a SuperClass 79 CSE 2102 Examples from HTSS Specialization and Generalization Item Generalization / \ / \ NonPItem PerishItem / \ \ / \ \ DeliItem DairyItem ProduceItem Specialization class PItem : public Item { protected: food_state Environ; int Days; void ItemSpecificPrint(); public: virtual void CreateNewItem(); virtual void PrintItem(); virtual void PrintPerish(); virtual void UpdateItem(); void PrintDaysFoodState(); }; class DeliItem : public PItem {protected: float Weight; float CostPerLb; void ItemSpecificPrint(); public: virtual void CreateNewItem(); virtual void PrintItem(); virtual void PrintPerish(); virtual void UpdateItem(); void PrintWeightandCost(); }; 80 Specification Inheritance & Example CSE 2102 Specification Classes Share Common Interface (Superclass) Specification Class: An Abstract Interface Similar to Java’s Interface Designers Construct Unified Interface that is Sharable by Multiple Team Members Data-Oriented Function-Oriented GraphicalObject / \ \ / \ \ Ball Wall Hole Menu / \ / \ PrintMenu SaveMenu 81 Construction Inheritance & Example CSE 2102 Construction Subclass Inherits Majority of Functionality from its Superclass Subclass may Extend, Limit, or Vary the Functionality of Superclass Dictionary / \ / \ SymbolTable HashTable LinkedList / \ \ / \ \ Queue Set Stack 82 Variance Inheritance & Example CSE 2102 Variance Classes have Similar Implementations but Unrelated Abstract Views Result May Not Directly Aid Designer PointingDevice / \ \ / \ \ TouchPad Mouse Tablet Key Issues • Share Common Abstraction • Different Implementations • Methods in TouchPad, Mouse, etc., Override Methods in PointingDevice 83 Combination Inheritance & Example CSE 2102 Combination Use of Multiple Inheritance Combines Two or More Parents Allows Designers to View Design from Different Perspectives Faculty Student \ / \ / TeachingAsst MeatItem ProduceItem \ / \ / DelItem 84 Extension Inheritance & Example CSE 2102 Extension New Abilities are Added to Subclass Allows Designers to Reuse Prior Designs Requires Method(s) of Superclass to be Overridden Window / \ / \ FixedColorW VarColorW | Key Issues BWWindow • Going from 1 to 2 Colors FixedColorW - BWWindow • Expanding Capabilities 85 Limitation Inheritance & Example CSE 2102 Limitation Subclass has more Restricted Behavior Typically to Extend Existing Class Library Inverse of Extension Also Supports Design Reuse DEQueue / \ / \ Queue Stack / \ LIFO FIFO Key Issues • Going from Two-Direction Queue to Ltd. Abstractions • Limiting Functionality 86 Memory Layout Inheritance CSE 2102 Person String: Name String: Addr Student Float: GPA Undergrad Instance: ug1 Name: “John” Addr: “23 Main Street” GPA: 3.5 Dorm: “ Buckley” Major: “ Computer Science” Undergrad String: Dorm String: Major 87 Memory Layout Inheritance CSE 2102 Student: String: Name String: Addr Enum: College Profile myInfo Profile Student Instance: s1 Name: “John” Addr: “23 Main Street” myInfo: Profile Instance: p1 GPA: 3.5 Dorm: “ Buckley” Major: “ Computer Science” Float: GPA String: Dorm String: Major 88 Benefits of Inheritance CSE 2102 Software Reusability Inherited Characteristics Often Represents Compiled and Tested Code/Behavior Reuse in Future Products Design and Program Families Design and Code Sharing Two or More Subclasses of the Same Superclass Share Code Redundancy is Reduced Reliability/Testing Enhanced Inherit from Existing Subclass that has been Utilized and Exercised 89 Benefits of Inheritance CSE 2102 Software Components Promotes the Concept of Reusable Components and Software Factory Combine Rather than Construct JavaBeans and APIs, Ada95 Packages, etc. Rapid Prototyping Utilization of Reusable Components Incremental Design and Development Delivery of Multiple Prototypes Faster to Market All Benefits Apply to Design, Development, and Maintenance! 90 The Cost of Inheritance CSE 2102 Execution Speed Compile-Time Overhead Due to Inheritance Many Decisions Related to Inheritance Must Occur at Runtime We’ll Explore this Shortly Program Size Libraries are Large, and if Only Static Linking, Size Grows Good News: Dynamic Linking Techniques are Improving Improve Runtime Environment Platform Independence (Java) Impacts both Speed and Size 91 The Cost of Inheritance CSE 2102 Message Passing Overhead An Overuse of Messages is akin to an Overuse of Procedures/Functions in C or Pascal Messages that Pass Arrays Increase Overhead To Find “Correct” Method, Must Search Object, Parent, Grandparent, etc. Remote Messages for Distributed Object Computing (CORBA, Java RMI) Program Complexity For Any New Paradigm, Software Engineers Must Acquire Appropriate Skills Despite HW Increases, Software Size and Complexity Continues to Grow! 92 Overloading CSE 2102 The Ability to Define Two or More Methods with the Same Names and Different Signatures A Feature of Programming Language Available in OO and Non-OO Languages Present in Current Languages, e.g., ‘+’ Means Integer Addition Real Addition Set Union (Pascal) OO Design and Programming Allows us to Define our own Types (Classes) Overload Operations (+, -, *, ++, etc.) Overload Methods 93 Overloading in a Stack Example CSE 2102 class stack { private: char* st, top; int size; public: void stack(int x) {top = st = new char[x]; size = x;} void stack() {top = st = new char[100]; size = 100;} // push, pop, top, etc., Omitted }; main() { stack S1(10); // stack S2; // // // } S1 20 15 10 Creates a char Stack with 10 Slots Default, no Parameter Supplied Creates a char Stack with 100 Slots Size of S2 Might not be Known to User! 5 S2 20 15 10 5 … etc ... 94 Overloading in HTS CSE 2102 class Item { private: int UPC, OnShelf, InStock, ROLimit; // Etc... As Previously Given public: Item(); // The Constructor // Etc... Others as Previously Given Item operator--(){ this->OnShelf--; this->InStock--; } }; main() { Item I1; Status s; s = I1.Create_New_Item(123, OJ, 10, 30, ...); I1--; // Reduces I1.OnShelf and I1.InStock // Now Contain 9 and 29 Respectively } 95 Important Implementation Concepts CSE 2102 Message Passing Method is a Member Function Message Passing: Invoking a Method receiverObject.MemberFunctionName( Automatic Variables Created within Function/Released at End Stack-Based Allocation No User Control/Intrevention Dynamic Variables Created on Demand by Explicit Invocation Heap-Based Allocation May Require Memory Management Why are A/D Variables Important to Design? 96 Important Implementation Concepts CSE 2102 Lifetime: Execution Period that Space Must Remain Allocated to Variable Scope: Portion of Program in Which Variable May Appear and be Utilized Immutable Values: Assigned Once, Can’t Change Constants Known at Compile Time Immutable Values Set at Runtime (UPC Code) Typing of Variables Static (Compile): C++, Java, Ada95 Dynamic (Runtime): Smalltalk, Lisp, … Strongly-Type Languages (Ada95 and Java) Language Does Not Allow Variable of One Type to hold Value of Different Type 97 Important Implementation Concepts CSE 2102 Static Binding: Method Bound to Message Based on Characteristics of Variable SE Must Track Type of Object Method Looked-Up at Compile Time Compile Detects Inappropriate Method Calls Dynamic Binding: Method Bound to Message Based on Characteristics of Value (Object) Runtime Search for Type of Object When Message is Passed (Method is Invoked) May Yield Runtime Error May Find/Execute “Inappropriate” Method Late Binding: Matching Message Invoked to Correct Method at Runtime 98 Remaining Object-Oriented Concepts CSE 2102 Polymorphism Definition and Illustration Attainment and Benefits Generics Type-Parameterizable Classes Examples using C++ Concepts that Impact Design and Development Substitutability Mutability Specialization via Constraints Material from “Fundamentals of ObjectOriented Databases”, pgs. 1-34, Zdonik/Maier. 99 Defining Polymorphism CSE 2102 Polymorphism is the Ability of a Variable to Hold more than One Type of Value, e.g., Subtypes of a Common Parent Variables P: Person; F: Faculty; S: Student; P F S //Supertype can Hold Instance of //Subtype, but NOT REVERSE! P = F; P = S; // Treat Faculty as Person // Treat Student as Person 100 CSE 2102 Definition of Polymorphism/Dispatching Polymorphism via Dispatching Allows a Runtime or Dynamic Choice of the Method to be Called based on the Class Type of the Invoking Instance Concept is only Useful in the Context of Inheritance Benefits of Polymorphism/Dispatching: Offers More Versatility in Hierarchy and Code Development Promotes Reuse and Evolution of Code Makes Code More Generic and Easier to Develop and Debug Polymorphism/Dispatching Incurs Cost or Overhead at both Compile and Runtime! 101 Illustrating Polymorphism/Dispatching CSE 2102 Consider Previous Example Person Name SSN Employee Dept Yrs Faculty Rank Dean School Student Dorm GPA UnderGrad Year Grad Program Degree Define Print_Info Method for Each Class Can Correct Print_Info Method be Called Automatically Based on Type of Instance Variable? 102 CSE 2102 Illustrating Polymorphism/Dispatching P Person Object Repository E F Steve “Faculty” S D U G Lois “Graduate” Ed “Faculty” Tom Mary “Dean” “UnderGrad” What’s True About Each Person? 103 Illustrating Polymorphism/Dispatching CSE 2102 Print_Info Methods Defined as Follows: Person::Print_Info() {Prints Name and SSN} Employee::Print_Info() {Calls Person::Print_Info(); Prints Dept and Yrs; } Student::Print_Info() {Calls Person::Print_Info(); Prints Dorm and GPA; } Faculty::Print_Info() {Calls Employee::Print_Info(); Prints Rank; } Print_Info Also for Dean, UnderGrad, Grad 104 CSE 2102 Illustrating Polymorphism/Dispatching Person Object Repository Steve “Faculty” Lois “Graduate” Ed Tom “Faculty” “UnderGrad” Mary “Dean” Suppose Iterate Through Instances of Person Repository For Each Instance, Call Method Print_Info() How Does One Determine the “Correct” Method to Call? What are the Compile Time Checks? Compile Time Guarantee? Runtime Checks? 105 Achieving Polymorphism/Dispatching CSE 2102 Build a Mixed List of Instances of Differing Types that Share a Common Ancestor To Begin, Declare Variables: FA1 = Faculty(Steve, 111, CSE, 7, AssocP); UG1 = UnderGrad(Rich, 222, Towers, 3.5, Senior); GR1 = Grad(Don, 333, OffCampus, 3.75, CSE, PhD); Define a LIST Class of Persons LIST is a Collection Class that Allows a Set of One or More Person Instances to be Stored LIST is an OO Version of Linked List Define LIST Methods for: LIST::Add_Person(Person P); LIST::Print_A_Member(); 106 Achieving Polymorphism/Dispatching CSE 2102 LIST Class has the Method Implementation LIST::Print_A_Member() { Calls Print_Info(); } Augment Variable Declarations with: PTR PTR PTR PTR = POINTER TO CLASS FOR A LIST OF Persons; -> LIST::Add_Person(GR1); //Add ‘Don’ -> LIST::Add_Person(UG1); //Add ‘Rich’ -> LIST::Add_Person(FA1); //Add ‘Steve’ PTR Views All List Elements as Persons Person is Common (Root) Ancestor Shared by All Classes in Inheritance Hierarchy! 107 Achieving Polymorphism/Dispatching CSE 2102 Pictorially, a LIST of Persons is Created: +----------+ +----------+ +----------+ | Person | | Person | | Person | PTR ->| |-->| |-->| | | (Really | | (Really | | (Really | | Steve | | Rich | | Don | | Faculty) | |Undergrad)| | Grad) | +----------+ +----------+ +----------+ What Happens when PTR->Print_A_Member()? If PTR Referencing ‘Steve’ Instance? If PTR Referencing ‘Rich’ Instance? If PTR Referencing ‘Don’ Instance? When PTR->Print_A_Member()is Called, Recall that the Print_Info() Method is Invoked 108 Execution/Runtime Sequence of Polymorphism/Dispatching CSE 2102 Which Print_Info Method is Invoked? The Runtime Environment Dynamically Chooses the Correct Method Based on Instance Type When PTR References ‘Steve’/Faculty Instance then Faculty::Print_Info() When PTR References ‘Rich’/UnderGrad Instance then UnderGrad::Print_Info() When PTR References ‘Don’/Grad Instance then Grad::Print_Info() Runtime Environment will Also Check Ancestor Instances In Order to Find the Correct Method Correct Compilation Guarantees Method Will be Found at Runtime! 109 Benefits of Polymorphism/Dispatching CSE 2102 Focus on Extensibility! Easily Extend and Evolve the Class/Inheritance Hierarchy as New Kinds of Items are Needed Extension/Evolution Occurs without Recompilation of Person Class Library For Example: class Staff : public Employee { … } class Visitor : public Person { … } class Transfer : public Student { … } Previous LIST Code Works without Modification Application that Creates Person Instances May Need to be Modified and Recompiled 110 Generics CSE 2102 Classic Programming Problem Develop Stack or List Code in C that Applies to a Single Type (e.g., List of DeliItems) Need Same Code for ProduceItems, MeatItems, etc., Copy and Edit Original Code Minimal Reuse, Error Prone, Time Consuming What do Generics Offer? A Type-Parameterizable Class Abstracts Similar Behavior into a Common Interface Reusable and Consistent Class Illustrate via C++ 111 CSE 2102 A Generic Stack Class template <class T> stack { private: T* st, int top; int size; public: void stack(int x) {st = new T[x]; top = 0; size = x;} stack() {st = new T[100]; top = 0; size = 100;} ~stack() {delete st;} push(T entry) { st[top++] = entry;} }; main() { stack<int> S1(10); // Creates int Stack with 10 Slots stack<char> S2; // Creates char Stack with 100 Slots stack<Item> ItemDB(10000); // Stack of Grocery Items } 112 CSE 2102 A Generic Set Class template <class ItemType> class Set { DLList<ItemType>* _members; // Set Templates Uses Double-Linked List Template public: Set() { _members = new DLList<ItemType>(); } void Add(ItemType* member) {_members->queue(member);} void Remove(ItemType* member) {_members->remove(member);} int Member(ItemType* member) {return _members->isMember(member);} int NullSet(){return _members->isEmpty();} } main() { Set<int> IntSet; // Creates an Integer Set Set<Item> ItemDB; // Creates an Item Set } 113 Benefits of Generics CSE 2102 Strong Promotion of Reuse Develop Once, Use Often stack and Set Examples Eliminate Errors and Inconsistencies Between Similar and Separate Classes Simplifies Maintenance Problems Focuses on Abstraction and Design Promotes Correctness and Consistent Program Behavior Once Designed/Developed, Reused with Consistent Results If Problems, Corrections in Single Location 114 Important Comment on Typing Issues CSE 2102 Consider the Four Features of Subtyping: Substitutability: If B IS A, then B Can Occur where A is Expected. Static-Type Checking: Everything is Known at Compile Time Mutability: An Instance Changes Type at Run Time Specialization via Constraints: Allows the Further Restrictions of Instance Characteristics via Inheritance Claim: Only Three of Four Can Ever Exist in a Single Model! 115 Substitutability CSE 2102 Recall that Employee is a Subclass of Person Substitutability Allows Employee to be Utilized in any Context that Person is Permitted Implications of Substitutability P and E Variables of Person and Employee Assignment: P = E; Parameter Passing: If P is the type of a Parameter, E can be Substituted in its Place Polymorphism/Dispatching Allows Faculty, Grad, and UnderGrad to Substitute for Person NonPItem, DeliItem, DairyItem, etc., to Substitute for Item 116 Mutability CSE 2102 Mutability Allows an Instance to Dynamically Change its Type within an Executing Application Excellent Conceptual Example from CAD Consider Boxes and Thru-Hole As Thru-Hole Moves Does Its Type Change? Does it Become a Blind Hole? Does it Alter its Depth to be a Thru-Hole? Muting a Powerful Concept that Breaks Rules 117 Other Features CSE 2102 Static Type Checking – Compilation All Types Known All Decisions Made Specialization via Constraints Person Faculty Undergrad (BS) Student(BS/MS/PHD) Graduate (MS/PHD) Only Three out of Four Can Co-Exist…. Adding Fourth Causes Contradiction… 118 How Does Contradiction Occur? CSE 2102 Specialization via Constraints with Set_Degree Method (see Previous Slide) Assume Static TC, Substitutability, and Mutability Suppose: Var S: Student; U: Undergrad; S := U; // OK if Subst. and Mutab. Set_Degree (S, MS); //No Compile Error Runtime: Unless Static TC Weakend, the Wrong Set_Degree Operation will be Chosen 119 The role of analysis and design CSE 2102 Software construction may be partitioned into the following phases: Requirements analyses Software architecture Specification (high-level/early design) Detailed design Implementation and testing Maintenance and evolution Where does OO Analysis and Design fit? 120 The Role of Analysis and Design CSE 2102 Analysis Investigating the boundaries of a problem Determining WHAT needs to be done OO Analysis: Emphasis on finding objects and identifying concepts in the problem domain Design Development of a logical solution Defining HOW system fulfills WHAT OO design Emphasis on defining logical software objects that ultimately implement solution. 121 Guidelines for Designing Classes Specifying “Good” Classes CSE 2102 Identifying a good class is hard work A well-defined class is: Highly cohesive: A single design abstraction Promotes loose coupling: Minimal ties to other classes Sufficient: Captures “enough” characteristics for efficient and meaningful operation Complete: Characteristics provide wide range of useful capabilities for clients Primitive: Operations are implementable when given access to hidden data of class Non-redundant: No two classes same Predictable: Behaves as expected by the users. 122 Guidelines for Designing Classes Understanding the Utility of Classes CSE 2102 Three categories of software in application: Domain independent (20%) Applicable regardless of the domain Stack, list etc. Domain-specific (65%) Likely to be used in current and future projects Inventory control classes for supermarkets, auto parts, video tape rentals, etc. Application-specific (15%) Cannot be reused, special purpose Classes for a specific entity Organizations must strive for domain and organization specific reuse. 123 Guidelines for Designing Classes CSE 2102 Containment vs. inheritance Class D “Has-A” class C Class D has an attribute of type class C Instances of class C live within class D Class D “Is-A-Kind-Of” class C Class D needs to acquire all behavior of class C Class D is a specialization of class C Choose Inheritance if class B is used by other classes Containment if class B is dedicated to class A Designers must cooperate and communicate 124 The Emergence of Unified Modeling Language (UML) CSE 2102 UML is OO analysis and design equivalent of Java UML is a language for Specifying, visualizing, constructing and documenting the artifacts of software UML unifies: OO analysis and design: Booch OO modeling and design: Rumbaugh OO SE Jacobson A modeling language provides: Model elements: Concepts and semantics Notation: Visual rendering of model elements Guidelines: Hints and suggestions for using elements in notation 125 Characteristics of UML CSE 2102 Generic syntax for creating a logical model of the system Syntax is independent of: Any particular target language Software process Software tool Syntax is flexible and can be customized by userdefined extensions to accommodate any process, tool, and language 126 Seven Goals of UML CSE 2102 Ready-to-use, expressive visual modeling language that promotes development/exchange Extensibility/specialization of core concepts Independent of programming languages and development processes Formal basis for understanding language Encourage growth of OO tools market Support higher level design concepts Collaborations, frameworks, patterns, etc. Integrate the best practices of all OOD 127 UML Modeling Diagrams CSE 2102 User interaction diagrams Use-case diagrams Static structure diagrams Class diagrams and Object diagrams Behavior diagrams Statechart diagrams Activity diagrams Interaction diagrams Sequence diagram Collaboration diagram Implementation diagrams Component diagram Deployment diagram 128 Class Diagrams CSE 2102 A class is a standard UML construct used to detail the pattern from which objects will be produced at run time Classes are graphically represented as boxes with compartments for: Class name, private attributes, and public operations Properties, responsibilities, rules, modification history, etc. Designer develops classes as sets of compartments that grow over time to incrementally add functionality and features 129 CSE 2102 Example Class Diagram Customer + Account: Int + Name: String + Address: String + Balance: Float + AddCustomer() + DeleteCustomer() + GetBalance() Name Attributes Operations “+” indicates that the attribute/operation is public “-” indicates that the attribute/operation is private “#” indicates that the attribute/operation is protected 130 CSE 2102 Generalization/Specialization (Inheritance) Describes hierarchical relationship among classes Person Salesperson Customer 131 CSE 2102 Class Diagram: High Tech SuperMarket System Consider the process of updating the inventory in the high-tech supermarket system. Central to the process is an inventory order. An inventory assistant in the HTSS is responsible for managing a inventory order. In addition, each inventory assistant may be involved in managing several inventory orders. An inventory order is associated with a list of items. Each item in the list can be of three types, namely, snack item, liquor item, and canned item. Each inventory order is submitted to three wholesale stores. Each wholesale store caters to a specific set of items. For example, the Liquor Store is responsible for delivering liquor items. These three wholesale stores, are, namely, Liquor Store, Produce Store, and Snack Store. Construct a UML class diagram to model the process of inventory update in HTSS. 132 Class Diagram: HTSS CSE 2102 InvenAssist * 1 1 InvenOrder 1 1…3 1 ItemList WholeStore Item 1 LiqStore ProdStore SnStore * PerishItem NPerishItem 133 CSE 2102 UML Class Diagram Case Study Consider an information system to manage a group of doctors in a practice. Each doctor is associated with a list of patients that he/she treats. The patients are classified into three categories, according to their age. These categories include, child, adult, and senior. The doctors are classified according to their specialization into the following categories: pediatrician, oncologist, endocrinologist, and general practitioner. Each doctor is assigned a dedicated administrative assistant who is responsible for managing various functions such as maintaining appointments, collecting payments etc. Draw a UML class diagram to model the information system for the doctor’s office. 134 Common Design Flaws CSE 2102 Classes that directly modify the private data of other classes Provide operations in public interfaces Change private data only via operations Item from HTSS class Item { private: // Private Data float public: void RetailCost; // Public Methods UpdatePrice(float new_value); }; Change RetailCost via UpdatePrice() Do not access RetailCost directly 135 Summary on Design CSE 2102 We’ve Seen Wide Array of Design Modularization ADTs Responsibility Driven Design Core and Advanced OO Concepts Categories of Classes Typing Issues Critical to Understand All of These Issues and More for Successful Software Engineering 136 An Overview of Java CSE 2102 Java is a Third Generation, General Purpose, Platform Independent, Concurrent, Class-Based, Object-Oriented Language and Environment Java Composed of JDK and JRE Java Language Java Packages (Libraries) javac Compiler to Bytecode (p-code) JDB Java Debugger Java Interpreter - Platform Specific JDK: Java Development Environment http://www.javasoft.com/products/jdk/1.2/ JRE: Java Runtime Environment http://www.javasoft.com/products/jdk/1.2/jre/index.html 137 CSE 2102 Java and New Technologies (Mobile) 138 Packages In Java CSE 2102 Allows Related Classes to be Grouped into a Larger Abstraction Similar to Ada95 Packages Unavailable in C++ Utilization of Packages for SW Design and Development Components, Modularization, Groupings Enforcement by Compiler of Package Rules Overall, Packages Enhance the Control and Visibility to Fine-Tune Who Can See What When 139 The Java Language CSE 2102 Overview of Non-OO Capabilities Based on C/C++ No includes, typedefs, structures, groups Unicode Character Set - 34,168 Characters Automatic Coercions Not Supported Strongly-Type Language Variables in Java Primitive Types: ints, floats, booleans, Unicode chars Reference Types: arrays, classes, interfaces No Physical Pointers in Java! 140 The Java Language CSE 2102 Statements in Java - Resembles C and C++ Assignment/Expressions and Precedence for, while, do-while if-then, switch-case break, continue, label, return Exception Handling Similar to C++ try, throws, catch Blocks Strongly Integrated Throughout APIs 141 The Java Language Motivating the Class Concept CSE 2102 Conceptually, Classes are Structures/Records with Functions that are Encapsulated structure { int char* float Item UPC, OnShelf, InStock, ROLimit; Name; RCost, WCost; Status NameCost* void Boolean Boolean Create_New_Item(int UPC, ...); Get_Item_NameCost(int UPC); Modify_Inventory(int UPC, int Delta) ; Check_If_On_Shelf(int UPC); Time_To_Reorder(int UPC); }; NameCost *nc; Item I1, I2; I1.Create_New_Item(...); nc = I2.Get_Item_NameCost(UPC); 142 The Java Language Object-Oriented Features CSE 2102 Class - similar to C++ Class Classes have Members (Methods and Variables) Members Tagged Using Keywords private: Typically, Inaccessible public: Potential to be Accessible protected: Accessible via Inheritance package: Accessible within Package Involve Visible Between Classes, Within Packages, and Due to Inheritance 143 Classes in Java CSE 2102 A Supermarket Item Keywords must be Utilized for Each Attribute or Method Declaration class Item { private String private int private double protected double public public void public boolean public int UPC, Name; Quantity; RetailCost; WholeCost; Item() { ... }; finalize() { ... }; Modify_Inventory(int Delta){...}; Get_InStock_Amt() {return Quantity;}; }; 144 Classes in Java CSE 2102 class Item { private String private int private double protected double public public void public boolean UPC, Name; Quantity; RetailCost; WholeCost; Item() { ... }; finalize() { ... }; Modify_Inventory(int Delta) { int i = Get_InStock_Amt (); if (Delta >= 0) { Quantity += Delta; return true; } else { return false;} }; public int Get_InStock_Amt() {return Quantity;}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(); {...}; }; 145 Visibility of Attributes/Methods CSE 2102 Class Members (Attributes and Methods) Visibility Tags for Members Private: Visible only to Class Protected: Visible to Class and Other Classes within Package Public: Visible to Class, Other Classes within Package, and if Class is Public, Visible to Other Packages/Classes No Tag: Visible Only to Other Classes within Defining Package Java's Controlled Sharing within/between Packages not Supported in C++ Abstraction/Encapsulation Superior in Java! 146 Inheritance - Two Roles CSE 2102 Controlled Sharing Between Classes Generalization vs. Specialization Treat Instances of Different Classes in a Uniform Fashion Polymorphism and Dynamic Binding Inheritance in Java Item / DeliItem | SaladItem \ ProduceItem class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... }; 147 CSE 2102 Designing and Developing Java Classes Encapsulation Capabilities of Java Classes (Data + Operations) - ADTs Packages - Collections of “Related” Classes Class Declaration: Access Modes and Variable Members Constructors and Class Bodies Method Declaration and Access Modes Class and Instance Members Garbage Collection 148 Class Definition CSE 2102 Member Variable Member Methods public class Stack { private Vector items; public Stack() { items = new Vector(10); } public Stack(int numElem) { items = new Vector(numElem); } public Object push(Object item) { item.addElement(item); return item; } public synchronized Object pop() { int len = items.size(); Object obj = null; if (len == 0) throw new EmptyStackException(); obj = items.elementAt(len - 1); items.removeElementAt(len - 1); return obj; } public boolean isEmpty() { if (items.size() == 0) return true; else return false; } } Class Declaration Constructors Class Body 149 Packages CSE 2102 A package is a Collection of Related Classes and Interfaces that Provides Access Protection and Namespace Management File Name and Package Name Identical Packages are Imported via the import Keyword package graphics; class Circle extend Graphic implements Draggable { ... } class Rectangle extends Graphic implements Draggable { ... } interface Draggable { ... } 150 Access Modes CSE 2102 Constructors and Members can be defined as: public: Any other class can invoke them. protected: Only subclasses and classes in the same package can invoke them. private: Only accessible within the class. package: Accessible only to other classes and interfaces declared in the same package (default if omitted). Controls Encapsulation and Allows Evolvability with Minimal Impact on other Classes that use the Members Deciding Appropriate Access Mode Determines Security and Ensures that Data Remains in a Consistent State. 151 Constructors CSE 2102 Utilized to Create a new Class instance by Reserving Sspace for the Member Variables Rectangle rect = new Rectangle(); Member Variable Initialization Possible Constructors Mimic Class Name with No Return Type Default Constructor with Empty Argument List Constructors may be Overloaded 152 Variable Members CSE 2102 Declaration (Class Body) Defines the Type of a Variable Instantiation (Constructor) Reserves Memory for the New Instance Initialization Assign Initial Value(s) accessLevel static final transient volatile type name Indicates the access level of this member Declares a class member Indicates that it is constant This variable is transient This variable is volatile The type and name of the variable 153 Method Members CSE 2102 Declaration Access Level public, protected, private, or package Return Type void or type return statement Either return the declared type or a subtype Name Overloading Overriding Arguments List of variable declarations Cannot include methods Argument names may hide member names: this 154 CSE 2102 Method Members (cont.) accessLevel static abstract final native synchronized returnType methodName (paramlist) throws exceptions Access level for this method This is a class method This method is not implemented Method cannot be overriden Method implemented in another language Method requires a monitor to run The return type and the method name The list of arguments The exceptions thrown by this method 155 Example CSE 2102 public class Point { public int x = 0; public int y = 0; Default Constructor public void move(int newX, int newY) { x = newX; y = newY; } aLineObject Line Instance origin end } public class Line { public Point origin; public Point end; public Line() { origin = new Point(); Overloading end = new Point(); } public Line(Point origin, Point end) { this.origin = origin; this.end = end; Hiding } x x y y Point Instances } 156 Class and Instance Members CSE 2102 Class Members are Defined with the Keyword static Class Variables and Class Methods are Associated with the Class Rather than each of its Instances Class Variables are Shared Among all Instances JRE Creates one copy of Class Variables the First Time it Encounters a Containing Instance Class Methods only Operate on Class Variables Class Bariables declared as final are constants Class Members are Accessible without the need to Instantiate the Class className.classMethod(); className.classVar = 10; 157 CSE 2102 Class and Instance Members (Continued) class AnInteger { class AnInteger { int x; int x; public int x() { static public int x() { return x; return x; } } public void setX(int newX) static public void setX(int { newX){ x = newX; x = newX; } } class AnInteger { } } static int x; public int x() { return x; } public void setX(int newX) { … x = newX; AnInteger myX = new AnInteger(); AnInteger yourX = new AnInteger(); } myX.setX(1); } yourX.x = 2; System.out.println(“myX = “ + myX.x()); System.out.println(“yourX = “ + yourX.x()); … 158 Garbage Collection CSE 2102 Unreferenced Objects are Garbage Collected Automatically Memory is Freed for Later Reuse Garbage Collection runs in a Low Priority Thread, either Synchronously or Asynchronously The finalize() Method is Inherited from Object and can be Overridden to Liberate Resources 159 Inheritance in Java CSE 2102 Basic Definitions and Concepts Generalization vs. Specialization Subclass vs. Superclass Acquisition Rules What Does Superclass Pass to Subclass? What Does Subclass Inherit from Superclass? What is Visible within Packages? Overriding vs. Overloading? Role of Public, Final, and Abstract Classes Java Interfaces for Design-Level Multiple Inheritance and Quasi Generics 160 Inheritance - Terms and Concepts CSE 2102 Every Class in Java is Derived from the Object Class Java Classes can be Organized into Hierarchies Using the extends Keyword Establishing Superclass/Subclass Relationships Between the Classes in Application A Superclass Contains Members Common to Its Subclasses - Generalization Subclasses Contain Members Different from Shared Superclass - Specialization Only Single Inheritance is Supported in Java at Implementation Level! 161 Subclass & Superclass CSE 2102 Subclass Subclass is a Class that Extends Another Class Inherits State and Behavior from all of its Ancestors Subclass can use the Inherited Member Variables and Functions or hide the Inherited Member Variables and Override the Inherited Member Functions Superclass Superclass is a Class’s Direct Ancestor 162 A Superclass in Java CSE 2102 A Supermarket Item Keywords must be Utilized for Each Attribute or Method Declaration class Item { private String private int private double protected double public public void public boolean public int UPC, Name; Quantity; RetailCost; WholeCost; Item() { ... }; finalize() { ... }; Modify_Inventory(int Delta){...}; Get_InStock_Amt() {return Quantity;}; }; 163 CSE 2102 Inheritance - Defining Subclasses in Java Item / \ DeliItem ProduceItem | SaladItem class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... }; 164 Members Inherited By a Subclass CSE 2102 Subclass Inherits all Public/Protected Members of a Superclass DeliItem Inherits Public/Protected from Item Subclass Inherits all Package Members of Classes in the same Package as the Subclass All superclass Members can be Declared with no Access Specification, if Subclass is in the Same Package as the Superclass 165 Members Not Inherited By A Subclass CSE 2102 Subclass does not Inherit Private Members of a Superclass DeliItem doesn’t Inherit Private from Item Subclasses do not Inherit a Superclass’s Member if the Subclass Declares a Member with Same Name Member Variables - Subclass Hides the Member Variable of the Superclass Member Methods - Subclass Overrides the one in the Superclass 166 CSE 2102 Hiding Member Variables and Overriding Member Methods class parentClass { boolean state; void setState() { state = true; } } class childClass extends parentClass { boolean state; void setState() { state = false; super.setState(); System.out.println(state); System.out.println(super.state) } } 167 Overriding Member Methods CSE 2102 Subclasses CANNOT Override Methods that are Declared to be Final in the Superclass Subclasses MUST Override Methods that are Declared as Abstract in the Superclass Subclasses MUST be Declared as Abstract if they do not Override Abstract Methods from the Superclass 168 Methods Inherited From Object Class CSE 2102 The Java “Object” Class Defines Basic State and Behavior of all Classes and Their Instances User Defined Classes can Override these Methods: clone equals finalize toString hashCode User Defined Classes Cannot Override: getClass notify notifyAll wait 169 Public, Final, and Abstract Classes CSE 2102 Public Classes Within Package, public Classes Become Visible to Outside World Public Members are Exported Final Classes Prohibits Subclassing for Security Final Class Prevents Access of Protected Members via Subclassing Not Supported in C++/Ada95 Abstract Classes Can't be Instantiated No Implementations for Abstract Methods 170 Final Classes and the “Final” Keyword CSE 2102 A Class is Declared as Final - the Class Cannot be Subclassed. For Security For Design A Method is Declared as Final in a Class - any Subclass Cannot Override that Method A Variable is Declared as Final - the Variable is a Constant and it Cannot be Changed 171 Abstract Classes And Methods CSE 2102 Abstract Classes Cannot be Instantiated Can only be Subclassed Keyword “abstract” before Keyword “class” is used to Define an Abstract Class Example of an Abstract Class is Number in the java.lang Package Abstract Methods Abstract Classes may contain Abstract Methods This allows an Abstract Class to Provide all its Subclasses with the Method Declarations for all the Methods 172 A Sample Abstract Class CSE 2102 abstract class Item protected String protected int protected double public abstract abstract public public { UPC, Name; Quantity; RetailCost, WholeCost; Item() { ... }; void finalize(); boolean Modify_Inventory(int Delta); Get_InStock_Amt() {...}; Compute_Item_Profit() {...}; public int public double protected boolean Modify_WholeSale(double NewPrice);{...}; }; 173 CSE 2102 Another Abstract Class and Methods abstract class GraphicsObject{ int x, y; void moveTo(int x1,y1) { . . . . . } abstract void draw(); } class Circle extends GraphicsObject{ void draw() { . . . . . } } class Rectangle extends GraphicsObject{ void draw() { . . . . . } 174 Interfaces in Java CSE 2102 Design-Level Multiple Inheritance Java Interface Set of Methods (no Implementations) Set (Possibly Empty) of Constant Values Interfaces Utilized Extensively Throughout Java APIs to Acquire and Pass on Functionality Threads in Java - Multiple Concurrent Tasks Subclassing from Thread Class (java.lang API) Implementing an Interface of Runnable Class 175 CSE 2102 A Sample Interface in Java Teaching Student / \ UnderGrad Graduate Employee | Faculty interface Teaching { int NUMSTUDENTS = 25; void recordgrade(Undergrad u, int score); void advise(Undergrad u); ... etc ... } class Graduate extends Student implements Teaching{ ...} class Faculty extends Employee implements Teaching{ ...} recordgrade() Different for Graduate & Faculty 176 CSE 2102 Quasi Generics in Java interface Coll { int MAXIMUM = 500; void add(Object obj); void delete(Object obj); Object find(Object obj); int currentCount(); } class Set implements Coll{ void add(Object obj){ ... } void delete(Object obj){ ... } } class Queue implements Coll{ void add(Object obj){ ... } void delete(Object obj){ ... } } 177 Polymorphism and Object Serialization in Java CSE 2102 Polymorphism Polymorphism via Dispatching Allows a Runtime or Dynamic Choice of the Method to be Called based on the Class Type of the Invoking Instance Promotes Reuse and Evolution of Code Polymorphism/Dispatching Incurs Cost or Overhead at both Compile and Runtime! Serialization Conversion of Object to Format that Facilitates Storage to File or Transfer Across Network Process Controlled via API with Minimal Interaction by Software Engineer 178 Polymorphism CSE 2102 Substitutability Whenever Value of a Certain Type is Expected, a Subtype can also be Provided In Context of Inheritance, All Subclasses can be Treated as Common Root Class Simplifies Code and Facilitates Reuse Static Type Type Defined in the Variable Declaration Dynamic Type Type of the Actual Value held by the Variable at Runtime 179 Polymorphism CSE 2102 A Variable is Polymorphic Whenever it may have Different Static and Dynamic Types Static Variable I1 Defined with Type Item Dynamic Variable Access Allows I1.Print() to be Invoked on DeliItem, ProduceItem, etc., Instances Problems: Reverse Polymorphism: Can we get the Subtype Variable Back After Assigning its Value to a Supertype? Method Binding: When Invoking a Method on a Variable, should it be Selected According to its Static or Dynamic Type? 180 An Example CSE 2102 We have a class Ball, and two subclasses WhiteBall and BlackBall The SelectOne() method gets a WhiteBall and a BlackBall as arguments and returns one of them selected randomly Questions: What is SelectOne()’s return type? How can we know which ball was returned? SelectOne ? 181 CSE 2102 Dynamic Binding and Casting public class Ball { public String id = new String("I'm a ball"); public String GetId() { return id; } } public class WhiteBall extends Ball { public String id = new String("I'm white"); public String GetId() { return id; } public void OnlyWhite() { System.out.println("Yes, I'm white"); } } public class BlackBall extends Ball { public String id = new String("I'm black"); public String GetId() { return id; } public void OnlyBlack() { System.out.println("Yes, I'm black"); } } The static type of b is Ball, but its dynamic type is either WhiteBall or BlackBall. class balls { public static void main(String[] args) { WhiteBall wb = new WhiteBall(); BlackBall bb = new BlackBall(); Ball b = SelectOne(wb, bb); System.out.println(b.GetId()); System.out.println(b.id); if (b instanceof WhiteBall) { wb = (WhiteBall)b; wb.OnlyWhite(); } else { bb = (BlackBall)b; bb.OnlyBlack(); } } public static Ball SelectOne(WhiteBall w, BlackBall b) { if (Math.random() > 0.5) return w; else return b; } What is going to be printed? } 182 CSE 2102 Class Student (Superclass) - Maintains Student Information public class Student { // protected used to facilitate inheritance protected String name, SSN; protected float gpa; // constructor used to initialize object public Student(String n, String ssn,float g) { name = n; SSN = ssn; gpa = g; } public String getSSN() { return SSN; } // diplay student information public void print() { System.out.println("Student name: " + name); System.out.println(" SSN: " + SSN); System.out.println(" gpa: " + gpa); } } public String getName() { return name; } public float getGpa() { return gpa; } 183 Class Grad CSE 2102 public class Grad extends Student { private String thesis; public Grad(String name, String ssn, float gpa, String t) { // call parent's constructor super(name, ssn, gpa); thesis = t; } public String getThesis() { return thesis; } public void print() { super.print(); System.out.println(" } thesis: " + thesis); } 184 Class Undergrad CSE 2102 public class Undergrad extends Student { private String advisor; private String major; public Undergrad(String name, String ssn, float gpa, String adv, String maj){ super(name, ssn, gpa); advisor = adv; major = maj; } public String getAdvisor() { return advisor; } public String getMajor() { return major; } public void print() { super.print(); System.out.println(" System.out.println(" } advisor: " + advisor); major: " + major); } 185 CSE 2102 Class StudentDB import java.util.Vector; public class StudentDB{ private Vector stuList; // constructor public StudentDB(int size){ // allocate memory for vector stuList = new Vector(size); } // returns number of students stored public int numOfStudents() { return (stuList.size()); } public void insert(Student s) { stuList.addElement(s); } // search for student by name public Student findByName(String name){ Student stu = null; // temp student boolean found = false; int count = 0; int DBSize = stuList.size(); while ((count < DBSize)||(found == false)){ stu = (Student) stuList.elementAt(count); if (stu.getName().equals(name )) found = true; count++; } return stu; } 186 Class StudentDB (Continued) CSE 2102 public Student remove(String name) { Student stu = null; // temp student boolean found = false; int count = 0; int DBSize = stuList.size(); while ((count < DBSize) || (found == false)){ stu = (Student) stuList.elementAt(count); if (stu.getName().equals(name)) found = true; count++; } if (found == true) public void displayAll() { int DBSize = stuList.size(); for (int i = 0; i < DBSize; i++) { Student stu = (Student) stuList.elementAt(i); stu.print(); System.out.println(); } } } stuList.removeElementAt(coun t - 1); return stu; } 187 CSE 2102 Class MainInterface public class MainInterface { private StudentDB db; public static void main(String[] args) { MainInterface studentInt = new MainInterface(); studentInt.displayMenu(); } // constructor public MainInterface() { db = new StudentDB(5); } public void displayMenu(){ int option = 0; System.out.println("\n 1. Insert "); System.out.println(" 2. Delete "); System.out.println(" 3. Search "); System.out.println(" 4. Display "); System.out.println(" 5. Exit \n"); option = Console.readInt("Enter your choice: "); while (option > 0 && option < 5) { processOption(option); System.out.println("\n 1. Insert "); System.out.println(" 2. Delete"); System.out.println(" 3. Search "); System.out.println(" 4. Display "); System.out.println(" 5. Exit \n"); option = Console.readInt("Enter your choice: "); } } 188 CSE 2102 Class MainInterface (Continued) public void processOption(int option) { String name, SSN; float gpa; switch (option){ case 1: int type = Console.readInt("1. Grad or 2. Undergrad? "); name = Console.readString(“Name: "); SSN = Console.readString(“SSN: "); gpa = (float) Console.readDouble("gpa: "); if (type == 1){ String thesis = Console.readString("Enter thesis title:"); Student g = new Grad(name, SSN, gpa, thesis); db.insert(g); } 189 CSE 2102 Class MainInterface (Continued) else{ String advisor = Console.readString("Enter advisor:"); String major = Console.readString("Enter major: "); Student u = new Undergrad(name, SSN, gpa, advisor, major); db.insert(u); } break; case 2: name = Console.readString(”Name"); Student s = db.remove(name); s.print(); break; 190 Class MainInterface (Continued) CSE 2102 case 3: name = Console.readString("Enter name: "); Student stu = db.findByName(name); System.out.println(); stu.print(); break; case 4: System.out.println(); db.displayAll(); } } } 191