1 cse 2102 object-oriented design and development prof. steven a. demurjian, sr. computer science...

191
1 CSE 2102 Object-Oriented Design and Object-Oriented Design and Development Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-255 Storrs, CT 06269-2155 [email protected] http://www.engr.uconn.edu/ ~steve (860) 486 - 4818 Copyright © 2000 by S. Demurjian, Storrs, CT.

Upload: phillip-perry

Post on 12-Jan-2016

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

1

CSE

2102Object-Oriented Design and DevelopmentObject-Oriented Design and Development

Prof. Steven A. Demurjian, Sr.Computer Science & Engineering Department

The University of Connecticut371 Fairfield Road, Box U-255

Storrs, CT 06269-2155

[email protected]://www.engr.uconn.edu/

~steve(860) 486 - 4818

Copyright © 2000 by S. Demurjian, Storrs, CT.

Page 2: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

2

CSE

2102Overview of PresentationOverview of Presentation

Abstraction and Modularization ConceptsAbstraction and Modularization Concepts Quick Review Compare and Contrast

Exploring Transitional Design IssuesExploring Transitional Design Issues Revisiting Core Object-Oriented ConceptsRevisiting Core Object-Oriented Concepts

Encapsulation, Hiding, Inheritance, etc. Advanced Object-Oriented ConceptsAdvanced Object-Oriented Concepts

Polymorphism, Dispatching, Generics, etc. Exploring Concepts

Summary and DiscussionSummary and Discussion

Page 3: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

3

CSE

2102

As Software has Become more Complex, it As Software has Become more Complex, it Requires more Software EngineersRequires more Software Engineers

F. Brooks - Mythical Man Month - 1970sF. 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?WHY? Interconnectedness: Interdependencies in CodeInterconnectedness: Interdependencies in Code

Individual Portions can’t be Written in Isolation

Information Exchange Needed Between SEs Complexity Historically Controlled by Abstracting Complexity Historically Controlled by Abstracting

Away Less Important DetailsAway Less Important Details

Abstraction and ComplexityAbstraction and Complexity

Page 4: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

4

CSE

2102AbstractionAbstraction

Page 5: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

5

CSE

2102EncapsulationEncapsulation

Page 6: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

6

CSE

2102

ProceduresProcedures The “First” Abstraction Mechanism Repeated Execution of Same Code without

Duplication Inefficient at Information Hiding

Modules: Managing Name SpacesModules: 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

History of Abstraction History of Abstraction Procedures and ModulesProcedures and Modules

Page 7: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

7

CSE

2102ModuleModule

Page 8: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

8

CSE

2102

Proposed by B. Liskov (MIT) for CLU in 1975Proposed by B. Liskov (MIT) for CLU in 1975 ADTs Promote Application Development From ADTs Promote Application Development From

Perspective of Information and its UsagePerspective of Information and its Usage ADT Design Process: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 TypesADTs Correspond to User-Defined Data Types Analogous to Integer Data Type and +, -, *, etc.Analogous to Integer Data Type and +, -, *, etc.

Abstract Data Types (ADTs)Abstract Data Types (ADTs)

Page 9: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

9

CSE

2102

Consider the following Example Consider the following Example StackStack ADT: ADT:

Abstract Data Types (ADTs)Abstract Data Types (ADTs)

PublicInterface

User

PUSHPOPTOPEMPTY

Private Implementation

DesignerHead: Int;ST: Array[100] of Int;

Push(X Int)…End;

Int Pop()…End;

TOP

5

1015

20

PUSH

5

20 15 10 5

20 15 10 5

ST

Page 10: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

10

CSE

2102

Separation of Concerns and Modularity Separation of Concerns and Modularity Problem Decomposable into Components

Abstraction and Representation IndependenceAbstraction and Representation Independence Hiding Implementation of Components Changing without Impacting External View

Incrementality and Anticipation of ChangeIncrementality and Anticipation of Change Components are Changed, Added, Refined,

etc., as Needed to Support Evolving Requirements

CohesionCohesion: Well-Defined Component Performs a : Well-Defined Component Performs a Single Task or has a Single ObjectiveSingle Task or has a Single Objective

CouplingCoupling: Component Interactions are Known and : Component Interactions are Known and MinimalMinimal

ADT Design GuidelinesADT Design Guidelines

Page 11: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

11

CSE

2102

Object-Oriented DecompositionObject-Oriented Decomposition Decompose Problem into Agents which

Perform Operations Emphasize Agents that Cause Actions

Agents Comprised of Two PartsAgents 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 An Agent Can Only be Modified by Operations

Defined in either the Defined in either the Hidden ImplementationHidden Implementation or or PublicPublic InterfaceInterface

Object-Oriented ParadigmObject-Oriented Paradigm

Page 12: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

12

CSE

2102

Class Class The Type of an Agent Describes the Behavior

Object Object The Instance of a Class Represents Actual Data Manipulated by Agents Maintains the State of Object

MethodMethod Operation Defined on a Class Operates on ALL Instances of the Class

MessageMessage Indicates that an Object’s Method Invoked

Core Object-Oriented ConceptsCore Object-Oriented Concepts

Page 13: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

13

CSE

2102What is a Class?What is a Class?

Page 14: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

14

CSE

2102What is a Class ?What is a Class ?

class nameclass name

attributes:attributes:

operations:operations:

external external entitiesentities

thingsthings

occurrencesoccurrences rolesroles

organizational unitsorganizational units

placesplaces

structuresstructures

•A class is a generalized description of A class is a generalized description of a collection of similar objects.a collection of similar objects.•Object is an instance of a class.Object is an instance of a class.•Class exports:Class exports: -Operations used to manipulate instances-Operations used to manipulate instances -May export attributes.-May export attributes.

Page 15: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

15

CSE

2102Two Representations of a ClassTwo Representations of a Class

class name

attributes:

operations:

attributes:

operations

Page 16: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

16

CSE

2102

Operations (or Methods or Services)Operations (or Methods or Services)Defined on a ClassDefined on a Class

An executable procedure that is a part of a class An executable procedure that is a part of a class and operates on the data attributes defined as part and operates on the data attributes defined as part of the classof the class A method operates on all instances of a class A method is invoked via message passing

Page 17: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

17

CSE

2102MessagesMessages

sender object

attributes:

operations:

receiver object

attributes:

operations:

message: [receiver, operation, parameters]

message: [sender, return value(s)]

Messages - the means by which objects Messages - the means by which objects invoke each other’s methods.invoke each other’s methods.

Page 18: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

18

CSE

2102An Example Employee ClassAn Example Employee Class

Class Employee {

}

//Hidden ImplementationPrivate: //Instance Vars char[30] name; float salary;//Public InterfacePublic: void print_name(); void print_salary(); void update_salary(float i); Employee(char *n, float s);

Main(){//Declare ObjectsEmployee emp1(Steve,100.0);Employee emp2(Lois, 120.0);

//Pass Messages//Invoke Methodsemp1.print_name();emp1.print_salary();emp2.update_salary(10);emp2.print_name();emp2.print_salary();}

What’s Output of Main()?

Steve100.0Lois130.0

Conclusion: Each Object (emp1,emp2) has Own Independent State that is Accessible via Shared Public Interface of Class

Page 19: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

19

CSE

2102

Module Module Describes Both State and Behavior Module Employee Includes Instance

Variables, Operations, and Program Variables Single Instance Shared by All Users

Class Class Describes Only the Behavior Class Employee Omits Program Variables Multiple Independent Instances Share Same

Class Declaration but have Separate States Key Difference: Key Difference: Dynamic NatureDynamic Nature of Classes of Classes

Allows Instances to be Created as NeededAllows Instances to be Created as Needed

Modules vs. ADTs/ClassesModules vs. ADTs/Classes

Page 20: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

20

CSE

2102

Background and MotivationBackground and Motivation Transitional Design & Silver Bullet (Brooks) Law of Demeter/Responsibility-Driven Design

Object-Oriented Design IssuesObject-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”, Software Design,” and “Object-Oriented Design”, Chapter 108 and 109, Chapter 108 and 109, The Computer Science & The Computer Science & Engineering HandbookEngineering Handbook, Tucker (ed.), CRC Press, , Tucker (ed.), CRC Press, 22ndnd Edition, 2002. Edition, 2002.

Object-Oriented ConceptsObject-Oriented Concepts

Page 21: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

21

CSE

2102

What Does What Does Customer WantCustomer Want? ? What Does What Does Designer NeedDesigner Need? ? Comprehensive Object-Oriented Design Must: 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 KEY: Define the Problem and Understand its Domain and ScopeDomain and Scope

Concepts of Transitional DesignConcepts of Transitional Design

Page 22: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

22

CSE

2102Transitional Design - PracticeTransitional Design - Practice

Focus on Encapsulation, Hiding, and Inheritance Focus on Encapsulation, Hiding, and Inheritance Emphasize a Behavioral Perspective:Emphasize a Behavioral Perspective:

What's Encapsulated/Hidden? Actions/Responsibilities are Key! Interdependencies are Critical!

While Encapsulation and Hiding Typically Imply While Encapsulation and Hiding Typically Imply an Independence Among “Classes” (other than an Independence Among “Classes” (other than Inheritance), Our Claim is that Such a View is Inheritance), Our Claim is that Such a View is Artificial and Unrealistic!Artificial and Unrealistic!

Represent Represent “World” as it Occurs“World” as it Occurs, Not as we , Not as we Would Like it to Occur!Would Like it to Occur!

Page 23: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

23

CSE

2102Thoughts From Fred BrooksThoughts From Fred Brooks

““No Silver Bullet”, No Silver Bullet”, IEEE ComputerIEEE Computer, Apr. 1987, Apr. 1987 Common MotivationCommon 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, Focus on the Identification, Cultivation, Recognition and Reward of “Great Designers”Recognition and Reward of “Great Designers”

““Biting the Silver Bullet”, D. Harel, Biting the Silver Bullet”, D. Harel, IEEE IEEE ComputerComputer, Jan. 1992, Jan. 1992

Page 24: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

24

CSE

2102

Law of DemeterLaw of Demeter(Leiberherr, Northeastern University)(Leiberherr, Northeastern University)

Stress Encapsulation by Reducing Stress Encapsulation by Reducing Interdependencies Between Classes (Objects) Interdependencies Between Classes (Objects)

High Cohesion and No Coupling High Cohesion and No Coupling A Class Cannot Directly Manipulate (via Method) A Class Cannot Directly Manipulate (via Method)

Internal Representation of Another Class Internal Representation of Another Class Classes Developed and Analyzed Independently Classes Developed and Analyzed Independently Focus on Method Access and Message SendingFocus on Method Access and Message Sending

Only Objects in Parameter List of Methods Instance Variables of Class but NOT

Superclasses Global and Temporary Variables

Page 25: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

25

CSE

2102

Responsibility-Driven DesignResponsibility-Driven Design(Wirfs-Brock & Wilkerson, OOPSLA89)(Wirfs-Brock & Wilkerson, OOPSLA89)

Approach Emphasizes Responsibilities: Approach Emphasizes Responsibilities: “What actions is this object responsible for?” “What information does this object share?”

Three Perspective Client Model:Three Perspective Client Model: External Clients Subclass Clients Self Client

Focus on Actions and Behavior Focus on Actions and Behavior Interactions Inevitable! Interactions Inevitable! Key: Define Required InteractionsKey: Define Required Interactions

Page 26: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

26

CSE

2102Objects vs. ADTsObjects vs. ADTs

Objects Extend ADTs as follows: 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 BenefitsADT/OO Benefits:

Support Creation of Reusable Software Components

Creation and Testing in Isolation! SEs View Problem at Higher-Level of

Abstraction

Page 27: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

27

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

The ‘First’ and Most ‘Often’ Concern for The ‘First’ and Most ‘Often’ Concern for Newcomers to OO Concepts Newcomers to OO Concepts

Typical Answers: Typical Answers: High Cohesion, Low Coupling, Encapsulation Law of Demeter, Responsibility-Driven Design Comes with Experience and Time

Better Answer: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.

Page 28: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

28

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

Employee classEmployee class Private data:Private data:

Name Address SSN Salary

Public interface:Public interface: Create_employee() Give_Raise_Amount(Amount) Change_Address(New_Addr)

Based on an information perspective, focusing on Based on an information perspective, focusing on the idea that to track Employees a set of standard the idea that to track Employees a set of standard data and operations are needed data and operations are needed

Page 29: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

29

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

ATM_log class:ATM_log class: Private data:Private data:

Acct_name PIN_number

Public interface:Public interface: Check_database(Name) Verify_PIN(PIN) Log_on_Actions(Name,PIN) Reject()

Embodies the functions that take place to Embodies the functions that take place to authenticate an individual to an ATM sessionauthenticate an individual to an ATM session

Even with a functional view, information is needed Even with a functional view, information is needed to capture user input for verifying statusto capture user input for verifying status

Page 30: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

30

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

ATM_User:ATM_User: Private data:Private data:

Action Balance WD_Amt

Public interface:Public interface: Log_on_Steps() Acct_WithD() Check_Balance(Number) Deposit_Check()

User interface by capturing the different User interface by capturing the different interactions between the ATM and the userinteractions between the ATM and the user

Page 31: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

31

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

Start from the problem specification Start from the problem specification Objects include physical entities as well as Objects include physical entities as well as

concepts such as seating arrangement, payment concepts such as seating arrangement, payment scheduleschedule

Not all classes maybe explicit in the problem Not all classes maybe explicit in the problem statement and may rely on domain knowledge for statement and may rely on domain knowledge for identificationidentification

Objects frequently correspond to nouns in the Objects frequently correspond to nouns in the statementstatement

Page 32: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

32

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

An appointments system that will allow telephone An appointments system that will allow telephone callers to book an appointment with a doctor. The callers to book an appointment with a doctor. The caller will specify the day and the time when he caller will specify the day and the time when he wishes to be seen by a doctor.wishes to be seen by a doctor.

Tentative classes could be: Tentative classes could be: Appointment, system, telephone, caller, doctor, Appointment, system, telephone, caller, doctor,

day, time day, time Patient - from domain knowledge Caller and patient express the same information

but one is more meaningful in the context.

Page 33: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

33

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

Identifying operations:Identifying operations: Attributes Events in the scenarios Real-world behavior

Attributes:Attributes: Need operations to set and read attributes

Events in the scenarios: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.

Page 34: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

34

CSE

2102Choosing Objects and Classes Choosing Objects and Classes

Real world can also suggest the operations needed Real world can also suggest the operations needed to support a class :to support a class : Useful in broadening the scope of the class

beyond its immediate application. Operations should not overlap each other: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 Number of operations that have access to the data should be reduced to a minimum.should be reduced to a minimum.

Operations may refer to verbs in the problem Operations may refer to verbs in the problem descriptiondescription

Page 35: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

35

CSE

2102InheritanceInheritance

Page 36: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

36

CSE

2102Inheritance – Example #1Inheritance – Example #1

A vehicle registration system maintains A vehicle registration system maintains registration information about all types of vehicles registration information about all types of vehicles owned by individuals. These include the ones that owned by individuals. These include the ones that run on land, sail in water and fly in the air. The run on land, sail in water and fly in the air. The vehicles that run on the land include cars and vehicles that run on the land include cars and trucks, the vehicles that sail in the water include trucks, the vehicles that sail in the water include sailboats, ships, motorboats and yatchs, and the sailboats, ships, motorboats and yatchs, and the vehicles that fly in the air include airplane and vehicles that fly in the air include airplane and helicopters. Construct an inheritance hierarchy for helicopters. Construct an inheritance hierarchy for the vehicle registration system. the vehicle registration system.

Page 37: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

37

CSE

2102Inheritance – Example #2Inheritance – Example #2

Consider a shipping cost calculation system that Consider a shipping cost calculation system that calculates shipping costs for a batch of packages. calculates shipping costs for a batch of packages. Packages can be shipped via three methods, Packages can be shipped via three methods, namely, US Mail, FedEx or UPS. For each of these namely, US Mail, FedEx or UPS. For each of these three methods, the customer has a choice of using three methods, the customer has a choice of using either standard or priority shipping. The either standard or priority shipping. The calculation of the shipping costs differs depending calculation of the shipping costs differs depending on which method is used. Construct an inheritance on which method is used. Construct an inheritance hierarchy for the shipping cost system. hierarchy for the shipping cost system.

Page 38: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

38

CSE

2102Choosing Objects for BlackJackChoosing Objects for BlackJack

Consider ‘Naïve’Abstraction:Consider ‘Naïve’Abstraction:

Deck Hand Game+---------+ +-------+ +-------------------+| Shuffle | | Play | | +----+ +----+ || Deal | | Hit | | |Hand| |Hand| ... || Hit | | Stand | | +----+ +----+ || ... | | ... | | Operations? |+---------+ +-------+ +-------------------+

What's Been Ignored? What's Been Ignored? Multiple Decks of Cards? Modeling of Deck - Suits/Cards? Strategy for House?

Moral: Objects/Classes are Moral: Objects/Classes are Not a PanaceaNot a Panacea for for Comprehensive, Up-Front, Problem Exploration via Comprehensive, Up-Front, Problem Exploration via a Detailed Specificationa Detailed Specification

Page 39: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

39

CSE

2102

The High-Tech Supermarket System (HTSS)The High-Tech Supermarket System (HTSS) Description of Capabilities Modules and ADTs for HTSS

Categories of ClassesCategories of Classes Common Design FlawsCommon Design Flaws

Object-Oriented Design IssuesObject-Oriented Design Issues

Page 40: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

40

CSE

2102High-Tech Supermarket System (HTSS)High-Tech Supermarket System (HTSS)

Automate the Functions and ActionsAutomate the Functions and Actions Cashiers and Inventory Updates User Friendly Grocery Item Locator Fast-Track Deli Orderer Inventory Control

User System Interfaces 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

Page 41: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

41

CSE

2102The HTSS Software ArchitectureThe HTSS Software Architecture

ICICICIC

CRCRCRCR

CRCR

CRCR

ILILILIL

ILIL

SDOSDO

SDOSDO EDOEDO

EDOEDO

OrderOrder

PaymentPayment

ItemItemItemDBItemDBLocalLocalServerServer

Non-LocalClient Int.

InventoryInventoryControlControl

ItemDBItemDBGlobalGlobalServerServer

OrderDBOrderDB

SupplierDBSupplierDB

CreditCardDBCreditCardDB

ATM-BanKDBATM-BanKDB

Page 42: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

42

CSE

2102Programming with ModulesProgramming with Modules

Modular Design and Development Contains: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:Versatility in Design Approach:

Functional Modules for: Cashier, Scanner, Locator, Orderer, Inventory Controller, etc.

Informational Modules for Item, DeliItem, Receipt, Credit/Check.

Page 43: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

43

CSE

2102Modules in HTSSModules in HTSS

MODULE Cashier; MODULE Scanner; IMPORT Get_Item(UPC), ... Get_Credit_Info(AcctNum), END Scanner; Get_Deli_Item(UPC), ...; EXPORT Display_SubTot(), MODULE Locator; Display_Total(), ... Generate_Receipt(), ...; END Locator; {code for internal data and for MODULE Orderer; procedures and functions} ... END Cashier; END Orderer; MODULE Items; MODULE DeliItems; IMPORT {various I/O routines}; ... EXPORT Get_Item(UPC), END DeliItems; New_Item(UPC, Name, ...), Modify_Item(UPC, Integer), MODULE CreditCheck; Delete_Item(UPC), ...; ... anItem = RECORD END CreditCheck; UPC : INTEGER; NAME: STRING; SIZE: REAL; ... END;END Items;

Page 44: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

44

CSE

2102Advantages/Drawbacks of ModulesAdvantages/Drawbacks of Modules

Import/Export:Import/Export: Concept Similar to Public Interface Promotes Controlled Sharing Provides Hiding Facilitates Concurrent Engineering

Strong Parallels to ADTsStrong Parallels to ADTs No Concept of “No Concept of “InstancesInstances”” But, Still Emphasizes Functional SolutionBut, Still Emphasizes Functional Solution Like OO/ADT, Supports Representation Like OO/ADT, Supports Representation

IndependenceIndependence

Page 45: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

45

CSE

2102Programming with ADTsProgramming with ADTs

ADTs Promote Applications Development From ADTs Promote Applications Development From Perspective of Information and Its UsagePerspective of Information and Its Usage

ADT Design Process and Steps: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 UpProcess 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

Page 46: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

46

CSE

2102ADTs in HTSSADTs 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;

Page 47: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

47

CSE

2102ADTs in HTSSADTs 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;

Page 48: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

48

CSE

2102Advantages/Drawbacks of ADTsAdvantages/Drawbacks of ADTs

Advantages:Advantages: Abstraction is Promoted and Achieved Concurrent Engineering is Feasible Reuse and Evolution are Attainable Emphasizes Static System Behavior

Drawbacks:Drawbacks: Without Inheritance, Redundancies Likely Dynamic System Behavior Still Difficult Associations Between ADTs Difficult Only Inclusion Association Supported

Do Drawbacks Outweigh Advantages?Do Drawbacks Outweigh Advantages?

Page 49: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

49

CSE

2102

Responsibility-Driven DesignResponsibility-Driven Design(Wirfs-Brock & Wilkerson, OOPSLA89)(Wirfs-Brock & Wilkerson, OOPSLA89)

Approach Emphasizes Responsibilities: 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 Focus on Actions and Behavior Interactions Inevitable! Interactions Inevitable! Key: Define Required InteractionsKey: Define Required Interactions

Page 50: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

50

CSE

2102

CRC CardsCRC CardsClass, Responsibility, CollaboratorsClass, Responsibility, Collaborators

Index Cards - Each Card Defines a ClassIndex Cards - Each Card Defines a Class Front of Each CRC Card: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:Back of Each CRC Card: Data - Hidden from Users

Page 51: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

51

CSE

2102A CRC Card for HTSSA CRC Card for HTSS

Item: A Product Sold in a Supermarket.

ItemDBCreate a New Item Return an Item's UPC Return an Item's NameReturn 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

Hidden Data:Name: String; UPC: String; Rcost, Wcost: Real;Quantity, ReorderLevel: Integer; etc...

Page 52: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

52

CSE

2102Another CRC Card for HTSSAnother CRC Card for HTSS

ItemDB: All Item’s in Supermarket - repository.

InvControlItem

Insert a New Item Delete an Existing Item Find/Display Item Based on UPCFind/Display Item Based on NameFind/Display Item Based on QtyFind/Display Item Based on ReorderPrint All Items Find an Item in Database by UPCFind an Item in Database by NameFind the First ItemFind the Next Item

Hidden Data:AllItems: Array[1..MaxItem] of Item;CurrItem, LastItem: Integer Index; etc...

Page 53: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

53

CSE

2102Flight Management ExampleFlight Management Example

Capabilities Include: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 For Simplicity, Ignore Overbooking and Attempts to Cancel Unbooked Flightsto Cancel Unbooked Flights

Using this Terse Description - Develop a SolutionUsing this Terse Description - Develop a Solution We’ll Explore Alternatives ShortlyWe’ll Explore Alternatives Shortly

Page 54: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

54

CSE

2102

CRC Cards for Flight Example CRC Cards for Flight Example One SolutionOne Solution

Agent: Handles Ticketing for Passengers.

ReserveCancel

Display Transaction Menu Wait for TransactionCall Apropos Trans. Manager

Reserve: Actions for Making Reservation.

FlightScheduleIssue

Ask Schedule if Seats AvailableAsk Flight to Reserve SeatsAsk Issue to Generate Tickets

Cancel: Actions for Canceling Reservation.

FlightIssue

Ask Flight to Cancel SeatsAsk Issue to Generate Refund

Page 55: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

55

CSE

2102

CRC Cards for Flight Example CRC Cards for Flight Example One SolutionOne Solution

Schedule: Flight Interactions/Ticketing.

FlightGet No. Seats and Flight No. Ask Flight if No. Seats AvailableAsk Flight to Reserve Seats Ask Flight to Cancel Seats

Issue: Generate Ticket or Cancellation.

Issue TicketIssue Refund Check

Flight: Tracks Seat Info. for Flights.Compare No. Seats with No. AvailableRemove Seats from Free ListReturn Seat No. to Schedule Add Cancelled Seat No. to Free List

Page 56: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

56

CSE

2102

CRC Cards for Flight Example CRC Cards for Flight Example Critiquing First SolutionCritiquing First Solution

Schedule Flight Issue

Agent

Cancel

Reserve

Design Represents User PerspectiveDesign Represents User Perspective Highlight Interactions via CollaboratorsHighlight Interactions via Collaborators

Commonalties?Commonalties?Differences?Differences?Couplings?Couplings?

Page 57: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

57

CSE

2102

Another SolutionAnother SolutionCombine Reserve, Cancel, and IssueCombine Reserve, Cancel, and Issue

Agent: Handles Ticketing for Passengers.

ReserveCancel

Display Transaction Menu Wait for TransactionCall Apropos Trans. Manager

Reservations: Making/Canceling Reservations.

FlightScheduleIssue

Ask Schedule if Seats AvailableAsk Flight to Reserve SeatsAsk Issue to Generate TicketsAsk Flight to Cancel SeatsAsk Issue to Generate RefundIssue TicketIssue Refund Check

Page 58: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

58

CSE

2102

Yet Another SolutionYet Another SolutionCombine Schedule and FlightCombine Schedule and Flight

Schedule: Flight Interactions/Ticketing.

FlightGet No. Seats and Flight No. Ask Flight if No. Seats AvailableAsk Flight to Reserve Seats Ask Flight to Cancel SeatsCompare No. Seats with No. AvailableRemove Seats from Free ListReturn Seat No. to Schedule Add Cancelled Seat No. to Free List

What was Problem with Original Design?What was Problem with Original Design? What has Occurred in Redesign?What has Occurred in Redesign? Structuring Solution from Perspective of Structuring Solution from Perspective of Arrival/Departure of Flights Would Likely Arrival/Departure of Flights Would Likely Yield Different Set of Classes!! Yield Different Set of Classes!!

Page 59: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

59

CSE

2102Categories of ClassesCategories of Classes

Data Managers -Data Managers - Maintain Data/State Information 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); };

Page 60: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

60

CSE

2102Categories of ClassesCategories of Classes

Data Sinks/Data SourcesData Sinks/Data Sources - Produce/Process Data - Produce/Process Data Generated on Demand or Maintained

class ItemDB {private: int Num_Items; int Curr_Item; Item* AllItems[Max_Items];

int FindFirstItem(); int FindNextItem(); int FindItemUPC(int code); int FindItemName(char* name); public: ItemDB(); // Constructor void InsertNewItem(Item* new_one); void DeleteExistingItem(int code); void FindDisplayItemUPC(int code); void FindDisplayItemName(char* name); void PrintAllItems(); };

Page 61: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

61

CSE

2102Categories of ClassesCategories of Classes

Data Manager Class Data Manager Class

ItemItem Class Contains the Class Contains the State of a Single ObjectState of a Single Object

Item I1, I2, I3;

Data Source/Sink Class Data Source/Sink Class

ItemDBItemDB is a Collection is a Collection or Set of Itemsor Set of Items

Item ItemDB[100];

I1“milk”

I2“peas”

I3“soda”

ItemDB

Page 62: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

62

CSE

2102Categories of ClassesCategories of Classes

View/ObserverView/Observer - Provide an Interface for User - 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();};

Page 63: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

63

CSE

2102Categories of ClassesCategories of Classes

Facilitator/HelperFacilitator/Helper - Used to Support Complex - Used to Support Complex TasksTasks E.g., GUI Libs, Strings, I/O Handler, etc.

For HTSS, Facilitator/Helpers as Follows: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?

Page 64: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

64

CSE

2102Methodological Issues for OO DesignMethodological Issues for OO Design

Design Grows Over Time Design Grows Over Time Begin by Identifying Classes Vital to ApplicationBegin by Identifying Classes Vital to Application Simulate Scenarios of Expected OperationSimulate Scenarios of Expected Operation

Identify New Classes Assign/Revise Methods to Classes Classes Demonstrate Flow of Control

Experimental Approach to Design - AdvantagesExperimental 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

Page 65: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

65

CSE

2102Early Stage of OO DesignEarly Stage of OO Design

Class AClass A Class BClass B Class CClass C

Class DClass D Class EClass E

Class AClass A

Class CClass C

Class FClass F

Class BClass B

Page 66: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

66

CSE

2102Methodological IssuesMethodological Issues

From First/Initial Attempts, Classes are Evolved From First/Initial Attempts, Classes are Evolved Towards “Complete” DesignTowards “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, IncludeAs Time Goes on, Include Inheritance: One Class is a Specialization of

Another Class Aggregation: One Class is a Component of

Another Class

Page 67: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

67

CSE

2102Later Stage of OO DesignLater Stage of OO Design

Class DClass D

Class FClass F

Class AClass A

Method A1Method A1Method A2Method A2Method A3Method A3

Class BClass B

Method B1Method B1Method B2Method B2Method B3Method B3Method B4Method B4

Class CClass C

Method C1Method C1Method C2Method C2

Int X, Y;Int X, Y;Char Z;Char Z;

Class EClass E

Real M, N;Real M, N;String S;String S;

Page 68: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

68

CSE

2102Common Design FlawsCommon Design Flaws

Classes that Directly Modify the Private Data of Classes that Directly Modify the Private Data of Other ClassesOther Classes Provide Operations in Public Interface Only Change via Operations Asking Class to Change Itself

Recall Item from HTSSRecall Item from HTSS

Only Change RetailCost via UpdatePrice()Only Change RetailCost via UpdatePrice()Do not Access RetailCost Directly from CashierDo not Access RetailCost Directly from Cashier

class Item { private: // Private Data float RetailCost; public: // Public Methods void UpdatePrice(float new_value); };

Page 69: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

69

CSE

2102Common Design FlawsCommon Design Flaws

Too Much Functionality in One ClassToo 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

int GetUPC(); char* GetName(); int GetInstockAmt(); int GetOnShelfAmt(); int GetQuantity(); int GetReorderAmt(); float GetRetailPrice(); float GetWholeSaleCost();

void UpdateName(char* item_name); void UpdateInstockAmt(int stock_amt); void UpdateOnShelfAmt(int shelf_amt); void UpdateReorderAmt(int reord_amt); void UpdateRetailPrice(float price); void UpdateWholeSaleCost(float wholesale); }

virtual void CreateNewItem(); virtual void PrintItem(); virtual void PrintPerish(); virtual void UpdateItemMenu(); virtual void UpdateItem(int portion); virtual char* ReturnType();

void PrintUPCName(); void PrintNamePrice(); void PrintInventory(); void PrintProfitInfo(); void PrintUPC(); void PrintName(); void PrintInstockAmt(); void PrintOnShelfAmt();

Page 70: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

70

CSE

2102Common Design FlawsCommon Design Flaws

A Class that Lacks FunctionalityA Class that Lacks Functionality Class Included at Early Design Stage Merge Two or More Classes Impact on

Inheritance Hierarchies? Classes that Have Unused FunctionalityClasses that Have Unused Functionality

Eliminate Unused Functions and Reevaluate Their Necessity

Classes that Duplicate FunctionalityClasses that Duplicate Functionality Combine with Existing Class Add Non-Duplicate Functionality

Page 71: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

71

CSE

2102

InheritanceInheritance Controlled Sharing of Between Classes

Generalization and Specialization Treat Instances of Different Classes in Uniform

Fashion - Leading to … Polymorphism/Dynamic BindingPolymorphism/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 ClassGeneric: 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)

Advanced Object-Oriented Concepts Advanced Object-Oriented Concepts

Page 72: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

72

CSE

2102

Consider a University ApplicationConsider a University Application Four Classes Have Been IdentifiedFour Classes Have Been Identified

Faculty Dean UnderGrad Grad Name Name Name Name SSN SSN SSN SSN Rank School Dorm Dorm Dept Dept Year Program Yrs Yrs GPA Degree GPA

To Successfully Utilize InheritanceTo Successfully Utilize Inheritance Distinguish Differences (Specialization) Identify Commonalties (Generalization)

Motivating Inheritance ConceptsMotivating Inheritance Concepts

Page 73: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

73

CSE

2102 One Solution:One Solution:

Person Faculty:Person Dean:Person Name Rank School SSN Dept Dept Yrs Yrs

UnderGrad:Person Grad:Person Dorm Dorm Year Program GPA Degree GPA

Pictorially:Pictorially: Person

Faculty Dean UnderGrad Grad

Is this Solution Adequate?Is this Solution Adequate?

Motivating InheritanceMotivating Inheritance

Page 74: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

74

CSE

2102 A Better Solution:A Better Solution:

Person Name SSN

Employee Student Dept Dorm Yrs GPA

Faculty Dean UnderGrad Grad Rank School Year Program Degree

Solution Utilizes Single InheritanceSolution Utilizes Single Inheritance Exactly One Parent for Each ClassExactly One Parent for Each Class Are we Done?Are we Done?

Motivating InheritanceMotivating Inheritance

Page 75: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

75

CSE

2102 Revising Example:Revising Example:

Person Name SSN

Employee Student Dept Dorm Yrs GPA

Faculty Dean UnderGrad Grad Rank School Year Program Degree

Superclass,Superclass, Supertype, Parent, Base Class Supertype, Parent, Base Class Subclass,Subclass, Subtype, Child, Derived Class Subtype, Child, Derived Class Descendants, Ancestors, SiblingsDescendants, Ancestors, Siblings

Motivating InheritanceMotivating Inheritance

Page 76: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

76

CSE

2102

Subclass Acquires Subclass Acquires InformationInformation and/or and/or OperationsOperations of a Superclass of a Superclass

Inheritance is a Transitive Operation Inheritance is a Transitive Operation Behavior and Information of a Subclass is a Behavior and Information of a Subclass is a

Superset of its Ancestors Superset of its Ancestors SubclassSubclass is More Refined than Superclass - is More Refined than Superclass - its its

SpecializedSpecialized SuperclassSuperclass contains Common Characteristics of contains Common Characteristics of

its Subclasses - its Subclasses - its Generalizedits Generalized

Defining InheritanceDefining Inheritance

Page 77: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

77

CSE

2102

Inheritance is Utilized when Two or More Classes Inheritance is Utilized when Two or More Classes are are Functionally and/or Informationally RelatedFunctionally and/or Informationally Related

In University Example, Common Data Basis of In University Example, Common Data Basis of Inheritance DecisionInheritance Decision

Other Bases for Inheritance could be:Other Bases for Inheritance could be: Common Methods Common Data and Methods

ReuseReuse Occurs from both Informational and Occurs from both Informational and Functional PerspectiveFunctional Perspective Information - No Replicated Variables Function - No Replicated Code

Defining InheritanceDefining Inheritance

Page 78: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

78

CSE

2102

Develop Inheritance Hierarchies that areDevelop Inheritance Hierarchies that are Extensible Reusable Evolvable

In Budd, Chapter 7, Excellent Discussion onIn Budd, Chapter 7, Excellent Discussion on Utilization of Inheritance: How Benefits of Inheritance: Why Impact of Inheritance: Cost

We’ll Review this MaterialWe’ll Review this Material

The Role of InheritanceThe Role of Inheritance

Page 79: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

79

CSE

2102

SpecializationSpecialization Most Common form of Inheritance to Refine

the Behavior of the SuperClass Differences are Pushed Down Hierarchy Allows Designers to Customize Classes

GeneralizationGeneralization Inverse of Specialization Commonalities of Multiple Classes are

Abstracted out to Form a SuperClass

Specialization and Generalization Specialization and Generalization InheritanceInheritance

Page 80: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

80

CSE

2102

Examples from HTSSExamples from HTSSSpecialization and GeneralizationSpecialization and Generalization

Item / \ / \ NonPItem PerishItem / \ \ / \ \ DeliItem DairyItem ProduceItem

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(); };

GeneralizationSpecialization

Page 81: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

81

CSE

2102

SpecificationSpecification 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

Specification Inheritance & ExampleSpecification Inheritance & Example

GraphicalObject / \ \ / \ \ Ball Wall Hole

Data-Oriented

Menu / \ / \PrintMenu SaveMenu

Function-Oriented

Page 82: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

82

CSE

2102

ConstructionConstruction Subclass Inherits Majority of Functionality

from its Superclass Subclass may Extend, Limit, or Vary the

Functionality of Superclass

Construction Inheritance & ExampleConstruction Inheritance & Example

Dictionary / \ / \SymbolTable HashTable

LinkedList / \ \ / \ \Queue Set Stack

Page 83: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

83

CSE

2102

VarianceVariance Classes have Similar Implementations but

Unrelated Abstract Views Result May Not Directly Aid Designer

Variance Inheritance & ExampleVariance Inheritance & Example

PointingDevice / \ \ / \ \TouchPad Mouse Tablet Key Issues

• Share Common Abstraction• Different Implementations• Methods in TouchPad, Mouse, etc., Override Methods in PointingDevice

Page 84: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

84

CSE

2102

CombinationCombination Use of Multiple Inheritance Combines Two

or More Parents Allows Designers to View Design from

Different Perspectives

Combination Inheritance & ExampleCombination Inheritance & Example

Faculty Student \ / \ / TeachingAsst

MeatItem ProduceItem \ / \ / DelItem

Page 85: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

85

CSE

2102

ExtensionExtension New Abilities are Added to Subclass Allows Designers to Reuse Prior Designs Requires Method(s) of Superclass to be

Overridden

Extension Inheritance & ExampleExtension Inheritance & Example

Window / \ / \FixedColorW VarColorW |BWWindow Key Issues

• Going from 1 to 2 Colors FixedColorW - BWWindow• Expanding Capabilities

Page 86: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

86

CSE

2102

LimitationLimitation Subclass has more Restricted Behavior Typically to Extend Existing Class Library Inverse of Extension Also Supports Design Reuse

Limitation Inheritance & ExampleLimitation Inheritance & Example

Key Issues• Going from Two-Direction Queue to Ltd. Abstractions• Limiting Functionality

DEQueue / \ / \ Queue Stack / \LIFO FIFO

Page 87: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

87

CSE

2102

Memory Layout Memory Layout InheritanceInheritance

PersonPersonStringString: : NameNameString: AddrString: Addr

StudentStudentFloat: GPAFloat: GPA

Undergrad Instance: ug1Name: “John”Addr: “23 Main Street”GPA: 3.5Dorm: “ Buckley” Major: “ Computer Science”

UndergradUndergradString: DormString: DormString: MajorString: Major

Page 88: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

88

CSE

2102

Memory Layout Memory Layout InheritanceInheritance

Student:Student:StringString: : NameNameString: AddrString: AddrEnum: CollegeEnum: CollegeProfile myInfoProfile myInfo

Student Instance: s1Name: “John”Addr: “23 Main Street”myInfo:

ProfileProfileFloat: GPAFloat: GPAString: DormString: DormString: MajorString: Major

Profile Instance: p1GPA: 3.5Dorm: “ Buckley” Major: “ Computer Science”

Page 89: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

89

CSE

2102

Software ReusabilitySoftware Reusability Inherited Characteristics Often Represents

Compiled and Tested Code/Behavior Reuse in Future Products Design and Program Families

Design and Code SharingDesign 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

Benefits of InheritanceBenefits of Inheritance

Page 90: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

90

CSE

2102

Software ComponentsSoftware Components Promotes the Concept of Reusable

Components and Software Factory Combine Rather than Construct JavaBeans and APIs, Ada95 Packages, etc.

Rapid PrototypingRapid Prototyping Utilization of Reusable Components Incremental Design and Development Delivery of Multiple Prototypes Faster to Market

All Benefits Apply to Design, Development, and All Benefits Apply to Design, Development, and Maintenance! Maintenance!

Benefits of InheritanceBenefits of Inheritance

Page 91: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

91

CSE

2102

Execution SpeedExecution Speed Compile-Time Overhead Due to Inheritance Many Decisions Related to Inheritance Must

Occur at Runtime We’ll Explore this Shortly

Program SizeProgram Size Libraries are Large, and if Only Static Linking,

Size Grows Good News: Dynamic Linking Techniques are

Improving Improve Runtime Environment

Platform IndependencePlatform Independence (Java) Impacts both (Java) Impacts both Speed and Size Speed and Size

The Cost of InheritanceThe Cost of Inheritance

Page 92: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

92

CSE

2102

Message Passing OverheadMessage 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 Program Complexity

For Any New Paradigm, Software Engineers Must Acquire Appropriate Skills

Despite HW Increases, Software Size and Complexity Continues to Grow!

The Cost of InheritanceThe Cost of Inheritance

Page 93: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

93

CSE

2102

The Ability to Define Two or More Methods with The Ability to Define Two or More Methods with the Same Names and Different Signaturesthe 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 OO Design and Programming Allows us to Define our own Types (Classes) our own Types (Classes) Overload Operations (+, -, *, ++, etc.) Overload Methods

OverloadingOverloading

Page 94: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

94

CSE

2102Overloading in a Stack ExampleOverloading in a Stack Example

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); // Creates a char Stack with 10 Slots stack S2; // Default, no Parameter Supplied // Creates a char Stack with 100 Slots // Size of S2 Might not be Known to User!}

20 15 10 5

20 15 10 5

S1S1

S2S2 … etc ...

Page 95: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

95

CSE

2102Overloading in HTSOverloading in HTS

class Item { private: int UPC, OnShelf, InStock, ROLimit; // Etc... As Previously Givenpublic: 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}

Page 96: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

96

CSE

2102

Message PassingMessage Passing Method is a Member Function Message Passing: Invoking a Method receiverObject.MemberFunctionName(

Automatic VariablesAutomatic Variables Created within Function/Released at End Stack-Based Allocation No User Control/Intrevention

Dynamic VariablesDynamic Variables Created on Demand by Explicit Invocation Heap-Based Allocation May Require Memory Management

Why are A/D Variables Important to Design?Why are A/D Variables Important to Design?

Important Implementation ConceptsImportant Implementation Concepts

Page 97: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

97

CSE

2102

LifetimeLifetime: Execution Period that Space Must : Execution Period that Space Must Remain Allocated to VariableRemain Allocated to Variable

ScopeScope: Portion of Program in Which Variable May : Portion of Program in Which Variable May Appear and be UtilizedAppear and be Utilized

Immutable ValuesImmutable Values: Assigned Once, Can’t Change: Assigned Once, Can’t Change Constants Known at Compile Time Immutable Values Set at Runtime (UPC Code)

Typing of VariablesTyping of Variables Static (Compile): C++, Java, Ada95 Dynamic (Runtime): Smalltalk, Lisp, …

Strongly-Type LanguagesStrongly-Type Languages (Ada95 and Java) (Ada95 and Java) Language Does Not Allow Variable of One

Type to hold Value of Different Type

Important Implementation ConceptsImportant Implementation Concepts

Page 98: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

98

CSE

2102

Static Binding:Static Binding: Method Bound to Message Based Method Bound to Message Based on Characteristics of Variableon Characteristics of Variable SE Must Track Type of Object Method Looked-Up at Compile Time Compile Detects Inappropriate Method Calls

Dynamic Binding:Dynamic Binding: Method Bound to Message Method Bound to Message Based on Characteristics of Value (Object)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 BindingLate Binding: Matching Message Invoked to : Matching Message Invoked to Correct Method at RuntimeCorrect Method at Runtime

Important Implementation ConceptsImportant Implementation Concepts

Page 99: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

99

CSE

2102Remaining Object-Oriented ConceptsRemaining Object-Oriented Concepts

PolymorphismPolymorphism Definition and Illustration Attainment and Benefits

GenericsGenerics Type-Parameterizable Classes Examples using C++

Concepts that Impact Design and DevelopmentConcepts that Impact Design and Development Substitutability Mutability Specialization via Constraints Material from “Fundamentals of Object-

Oriented Databases”, pgs. 1-34, Zdonik/Maier.

Page 100: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

100

CSE

2102

Polymorphism is the Ability of a Variable to Polymorphism is the Ability of a Variable to Hold more than One Type of Value, e.g., Hold more than One Type of Value, e.g., Subtypes of a Common Parent Subtypes of a Common Parent

Defining PolymorphismDefining Polymorphism

Variables P: Person; F: Faculty; S: Student;

//Supertype can Hold Instance of//Subtype, but NOT REVERSE!

P = F; // Treat Faculty as PersonP = S; // Treat Student as Person

P

F S

Page 101: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

101

CSE

2102

Polymorphism via Dispatching Allows a Polymorphism via Dispatching Allows a Runtime Runtime oror Dynamic Choice Dynamic Choice of the Method to be Called of the Method to be Called based on the Class based on the Class TypeType of the Invoking Instance of the Invoking Instance

Concept is only Useful in the Context of Concept is only Useful in the Context of Inheritance Inheritance

Benefits of Polymorphism/Dispatching: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

OverheadOverhead at both Compile and Runtime! at both Compile and Runtime!

Definition of Polymorphism/DispatchingDefinition of Polymorphism/Dispatching

Page 102: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

102

CSE

2102

Consider Previous ExampleConsider Previous Example Person Name SSN

Employee Student Dept Dorm Yrs GPA

Faculty Dean UnderGrad Grad Rank School Year Program Degree

Define Define Print_InfoPrint_Info Method for Each Class Method for Each Class Can CorrectCan Correct Print_InfoPrint_Info MethodMethod be Called be Called

Automatically Based on Automatically Based on Type of Instance Type of Instance VariableVariable?

Illustrating Polymorphism/DispatchingIllustrating Polymorphism/Dispatching

Page 103: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

103

CSE

2102Illustrating Polymorphism/DispatchingIllustrating Polymorphism/Dispatching

P

E S

F D U G

What’s TrueWhat’s TrueAbout EachAbout Each

Person?Person?

SteveSteveLoisLois

TomTom MaryMary

EdEd

Person Object RepositoryPerson Object Repository

““Faculty”Faculty”

“ “Dean”Dean”““UnderGrad”UnderGrad”

““Graduate”Graduate”

““Faculty”Faculty”

Page 104: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

104

CSE

2102

Print_InfoPrint_Info Methods Defined as Follows: 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

Illustrating Polymorphism/DispatchingIllustrating Polymorphism/Dispatching

Page 105: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

105

CSE

2102Illustrating Polymorphism/DispatchingIllustrating Polymorphism/Dispatching

Suppose Iterate Through Suppose Iterate Through Instances of Person Instances of Person RepositoryRepository

For Each Instance, Call For Each Instance, Call Method Method Print_Info()Print_Info()

How Does One How Does One Determine the “Correct” Determine the “Correct” Method to Call?Method to Call?

What are the What are the Compile Time

Checks? Compile Time

Guarantee? Runtime Checks?

SteveSteveLoisLois

TomTom

MaryMary

EdEd

Person Object RepositoryPerson Object Repository

““Faculty”Faculty”

“ “Dean”Dean”

““UnderGrad”UnderGrad”

““Graduate”Graduate”

““Faculty”Faculty”

Page 106: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

106

CSE

2102

Build a Build a Mixed List of InstancesMixed List of Instances of Differing of Differing Types that Share a Common Ancestor Types that Share a Common Ancestor

To Begin, Declare Variables: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 Define a LISTLIST Class of Class of PersonsPersons LISTLIST is a Collection Class that Allows a Set of

One or More Person Instances to be Stored LISTLIST is an OO Version of Linked List Define LISTLIST Methods for:

LIST::Add_Person(Person P);LIST::Add_Person(Person P); LIST::Print_A_Member();LIST::Print_A_Member();

Achieving Polymorphism/DispatchingAchieving Polymorphism/Dispatching

Page 107: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

107

CSE

2102

LISTLIST Class has the Method Implementation Class has the Method Implementation

LIST::Print_A_Member(){ Calls Print_Info();}

Augment Variable Declarations with:Augment Variable Declarations with:PTR = POINTER TO CLASS FOR A LIST OF Persons;PTR -> LIST::Add_Person(GR1); //Add ‘Don’PTR -> LIST::Add_Person(UG1); //Add ‘Rich’PTR -> LIST::Add_Person(FA1); //Add ‘Steve’

PTRPTR Views All List Elements as PersonsViews All List Elements as Persons PersonPerson is is Common (Root) AncestorCommon (Root) Ancestor Shared by Shared by

All Classes in Inheritance Hierarchy!All Classes in Inheritance Hierarchy!

Achieving Polymorphism/DispatchingAchieving Polymorphism/Dispatching

Page 108: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

108

CSE

2102

Pictorially, a LIST of Persons is Created:Pictorially, a LIST of Persons is Created: +----------+ +----------+ +----------++----------+ +----------+ +----------+ | Person | | Person | | Person || Person | | Person | | Person | PTR PTR ->| |-->| |-->| |->| |-->| |-->| | | (Really | | (Really | | (Really || (Really | | (Really | | (Really | | | SteveSteve | | | | RichRich | | | | DonDon | | | | FacultyFaculty) | |) | |UndergradUndergrad)| |)| | Grad Grad) |) | +----------+ +----------+ +----------+

What Happens when What Happens when PTR->Print_A_Member()PTR->Print_A_Member()?? If PTRPTR Referencing ‘Steve’ Instance? If PTRPTR Referencing ‘Rich’ Instance? If PTRPTR Referencing ‘Don’ Instance?

When When PTR->Print_A_Member()PTR->Print_A_Member()is Called, Recall is Called, Recall that the that the Print_Info()Print_Info() Method is Invoked Method is Invoked

Achieving Polymorphism/DispatchingAchieving Polymorphism/Dispatching

Page 109: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

109

CSE

2102

Which Which Print_InfoPrint_Info Method is Invoked? Method is Invoked? The Runtime Environment Dynamically Chooses The Runtime Environment Dynamically Chooses

the Correct Method Based on Instance Typethe Correct Method Based on Instance Type When PTRPTR References ‘Steve’/Faculty

Instance then Faculty::Print_Info() When PTRPTR References ‘Rich’/UnderGrad

Instance then UnderGrad::Print_Info() When PTRPTR References ‘Don’/Grad Instance

then Grad::Print_Info() Runtime Environment will Also Check Ancestor Runtime Environment will Also Check Ancestor

Instances In Order to Find the Correct MethodInstances In Order to Find the Correct Method Correct Compilation Guarantees Method Will be Correct Compilation Guarantees Method Will be

Found at Runtime!Found at Runtime!

Execution/Runtime Sequence of Execution/Runtime Sequence of Polymorphism/DispatchingPolymorphism/Dispatching

Page 110: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

110

CSE

2102

Focus on Extensibility!Focus on Extensibility! Easily Extend and Evolve the Class/Inheritance Easily Extend and Evolve the Class/Inheritance

Hierarchy as New Kinds of Items are NeededHierarchy as New Kinds of Items are Needed Extension/Evolution Occurs without Extension/Evolution Occurs without

Recompilation of Recompilation of PersonPerson Class Library Class Library For Example:For Example:

class Staff : public Employee { … } class Visitor : public Person { … } class Transfer : public Student { … }

Previous Previous LISTLIST Code Works without Modification Code Works without Modification Application that Creates Application that Creates PersonPerson Instances May Instances May

Need to be Modified and RecompiledNeed to be Modified and Recompiled

Benefits of Polymorphism/DispatchingBenefits of Polymorphism/Dispatching

Page 111: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

111

CSE

2102

Classic Programming ProblemClassic 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?What do Generics Offer? A Type-Parameterizable Class Abstracts Similar Behavior into a Common

Interface Reusable and Consistent Class

Illustrate via C++ Illustrate via C++

GenericsGenerics

Page 112: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

112

CSE

2102A Generic Stack ClassA 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 Slotsstack<char> S2; // Creates char Stack with 100 Slotsstack<Item> ItemDB(10000); // Stack of Grocery Items}

Page 113: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

113

CSE

2102A Generic Set ClassA 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 SetSet<Item> ItemDB; // Creates an Item Set}

Page 114: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

114

CSE

2102

Strong Strong Promotion of ReusePromotion of Reuse Develop Once, Use Often stackstack and SetSet Examples

Eliminate Errors and Inconsistencies Between Eliminate Errors and Inconsistencies Between Similar and Separate ClassesSimilar and Separate Classes Simplifies Maintenance Problems Focuses on Abstraction and Design

Promotes Correctness and Consistent Program Promotes Correctness and Consistent Program BehaviorBehavior Once Designed/Developed, Reused with

Consistent Results If Problems, Corrections in Single Location

Benefits of GenericsBenefits of Generics

Page 115: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

115

CSE

2102Important Comment on Typing IssuesImportant Comment on Typing Issues

Consider the Four Features of Subtyping: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 Claim: Only Three of Four Can Ever Exist in a Single Model!Single Model!

Page 116: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

116

CSE

2102

Recall that Recall that EmployeeEmployee is a Subclass of is a Subclass of PersonPerson Substitutability Allows Substitutability Allows EmployeeEmployee to be Utilized in to be Utilized in

any Context that any Context that PersonPerson is Permitted is Permitted Implications of SubstitutabilityImplications 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 AllowsPolymorphism/Dispatching Allows

Faculty, Grad, and UnderGrad to Substitute for Person

NonPItem, DeliItem, DairyItem, etc., to Substitute for Item

SubstitutabilitySubstitutability

Page 117: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

117

CSE

2102

Mutability Allows an Instance to Dynamically Mutability Allows an Instance to Dynamically Change its Type within an Executing Application Change its Type within an Executing Application

Excellent Conceptual Example from CADExcellent 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 RulesMuting a Powerful Concept that Breaks Rules

MutabilityMutability

Page 118: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

118

CSE

2102Other FeaturesOther Features

Static Type Checking – CompilationStatic Type Checking – Compilation All Types Known All Decisions Made

Specialization via ConstraintsSpecialization via Constraints

Only Three out of Four Can Co-Exist….Only Three out of Four Can Co-Exist…. Adding Fourth Causes Contradiction…Adding Fourth Causes Contradiction…

PersonPerson

FacultyFaculty Student(BS/MS/PHD)Student(BS/MS/PHD)

Undergrad (BS)Undergrad (BS) Graduate (MS/PHD)Graduate (MS/PHD)

Page 119: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

119

CSE

2102How Does Contradiction Occur?How Does Contradiction Occur?

Specialization via Constraints with Set_Degree Specialization via Constraints with Set_Degree Method (see Previous Slide)Method (see Previous Slide)

Assume Static TC, Substitutability, and MutabilityAssume Static TC, Substitutability, and Mutability Suppose:Suppose:

Var S: Student;Var S: Student; U: Undergrad; U: Undergrad;S := U; // OK if Subst. and Mutab.S := U; // OK if Subst. and Mutab.Set_Degree (S, MS); //No Compile ErrorSet_Degree (S, MS); //No Compile Error

Runtime: Unless Static TC Weakend, the Wrong Runtime: Unless Static TC Weakend, the Wrong Set_Degree Operation will be ChosenSet_Degree Operation will be Chosen

Page 120: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

120

CSE

2102The role of analysis and designThe role of analysis and design

Software construction may be partitioned into the Software construction may be partitioned into the following phases: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?Where does OO Analysis and Design fit?

Page 121: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

121

CSE

2102The Role of Analysis and DesignThe Role of Analysis and Design

AnalysisAnalysis Investigating the boundaries of a problem Determining WHAT needs to be done

OO Analysis:OO Analysis: Emphasis on finding objects and identifying

concepts in the problem domain DesignDesign

Development of a logical solution Defining HOW system fulfills WHAT

OO designOO design Emphasis on defining logical software objects

that ultimately implement solution.

Page 122: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

122

CSE

2102

Guidelines for Designing ClassesGuidelines for Designing ClassesSpecifying “Good” ClassesSpecifying “Good” Classes

Identifying a good class is hard workIdentifying a good class is hard work A well-defined class is: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.

Page 123: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

123

CSE

2102

Guidelines for Designing ClassesGuidelines for Designing Classes Understanding the Utility of Classes Understanding the Utility of Classes

Three categories of software in application: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 Organizations must strive for domain and organization specific reuse.organization specific reuse.

Page 124: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

124

CSE

2102Guidelines for Designing ClassesGuidelines for Designing Classes

Containment vs. inheritanceContainment 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

ChooseChoose Inheritance if class B is used by other classes Containment if class B is dedicated to class A

Designers must cooperate and communicateDesigners must cooperate and communicate

Page 125: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

125

CSE

2102

The Emergence of The Emergence of Unified Modeling Language (UML) Unified Modeling Language (UML)

UML is OO analysis and design equivalent of JavaUML is OO analysis and design equivalent of Java UML is a language forUML is a language for

Specifying, visualizing, constructing and documenting the artifacts of software

UML unifies:UML unifies: OO analysis and design: Booch OO modeling and design: Rumbaugh OO SE Jacobson

A modeling language provides:A modeling language provides: Model elements: Concepts and semantics Notation: Visual rendering of model elements Guidelines: Hints and suggestions for using

elements in notation

Page 126: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

126

CSE

2102Characteristics of UMLCharacteristics of UML

Generic syntax for creating a logical model of the Generic syntax for creating a logical model of the systemsystem

Syntax is independent of:Syntax is independent of: Any particular target language Software process Software tool

Syntax is flexible and can be customized by user-Syntax is flexible and can be customized by user-defined extensions to accommodate any process, defined extensions to accommodate any process, tool, and languagetool, and language

Page 127: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

127

CSE

2102Seven Goals of UMLSeven Goals of UML

Ready-to-use, expressive visual modeling Ready-to-use, expressive visual modeling language that promotes development/exchangelanguage that promotes development/exchange

Extensibility/specialization of core conceptsExtensibility/specialization of core concepts Independent of programming languages and Independent of programming languages and

development processesdevelopment processes Formal basis for understanding languageFormal basis for understanding language Encourage growth of OO tools marketEncourage growth of OO tools market Support higher level design conceptsSupport higher level design concepts

Collaborations, frameworks, patterns, etc. Integrate the best practices of all OODIntegrate the best practices of all OOD

Page 128: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

128

CSE

2102UML Modeling DiagramsUML Modeling Diagrams

User interaction diagramsUser interaction diagrams Use-case diagrams

Static structure diagramsStatic structure diagrams Class diagrams and Object diagrams

Behavior diagramsBehavior diagrams Statechart diagrams Activity diagrams

Interaction diagramsInteraction diagrams Sequence diagram Collaboration diagram

Implementation diagramsImplementation diagrams Component diagram Deployment diagram

Page 129: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

129

CSE

2102Class DiagramsClass Diagrams

A class is a standard UML construct used to detail A class is a standard UML construct used to detail the pattern from which objects will be produced at the pattern from which objects will be produced at run timerun time

Classes are graphically represented as boxes with Classes are graphically represented as boxes with compartments for:compartments for: Class name, private attributes, and public

operations Properties, responsibilities, rules, modification

history, etc. Designer develops classes as sets of compartments Designer develops classes as sets of compartments

that grow over time to incrementally add that grow over time to incrementally add functionality and featuresfunctionality and features

Page 130: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

130

CSE

2102Example Class DiagramExample Class Diagram

CustomerCustomer

+ Account: Int+ Account: Int+ Name: String+ Name: String+ Address: String+ Address: String+ Balance: Float+ Balance: Float

+ AddCustomer()+ AddCustomer()+ DeleteCustomer()+ DeleteCustomer()+ GetBalance()+ GetBalance()

NameName

AttributesAttributes

OperationsOperations

““+” indicates that the attribute/operation is public+” indicates that the attribute/operation is public““-” indicates that the attribute/operation is private-” indicates that the attribute/operation is private““#” indicates that the attribute/operation is protected#” indicates that the attribute/operation is protected

Page 131: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

131

CSE

2102Generalization/Specialization (Inheritance)Generalization/Specialization (Inheritance)

Describes hierarchical relationship Describes hierarchical relationship among classesamong classes

PersonPerson

SalespersonSalesperson CustomerCustomer

Page 132: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

132

CSE

2102

Class Diagram: High Tech SuperMarket Class Diagram: High Tech SuperMarket System System

Consider the process of updating the inventory Consider the process of updating the inventory in the high-tech supermarket system. Central to in the high-tech supermarket system. Central to the process is an inventory order. An inventory the process is an inventory order. An inventory assistant in the HTSS is responsible for assistant in the HTSS is responsible for managing a inventory order. In addition, each managing a inventory order. In addition, each inventory assistant may be involved in managing inventory assistant may be involved in managing several inventory orders. An inventory order is several inventory orders. An inventory order is associated with a list of items. Each item in associated with a list of items. Each item in the list can be of three types, namely, snack the list can be of three types, namely, snack item, liquor item, and canned item. Each item, liquor item, and canned item. Each inventory order is submitted to three wholesale inventory order is submitted to three wholesale stores. Each wholesale store caters to a stores. Each wholesale store caters to a specific set of items. For example, the Liquor specific set of items. For example, the Liquor Store is responsible for delivering liquor Store is responsible for delivering liquor items. These three wholesale stores, are, items. These three wholesale stores, are, namely, Liquor Store, Produce Store, and Snack namely, Liquor Store, Produce Store, and Snack Store. Construct a UML class diagram to model Store. Construct a UML class diagram to model the process of inventory update in HTSS.the process of inventory update in HTSS.

Page 133: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

133

CSE

2102Class Diagram: HTSSClass Diagram: HTSS

InvenOrderInvenOrderInvenAssistInvenAssist

WholeStoreWholeStore ItemListItemList ItemItem

PerishItemPerishItem NPerishItemNPerishItem

11 **

**11

11

111…31…3

11

Page 134: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

134

CSE

2102UML Class Diagram Case StudyUML Class Diagram Case Study

Consider an information system to manage a group of Consider an information system to manage a group of doctors in a practice. Each doctor is associated with a doctors in a practice. Each doctor is associated with a list of patients that he/she treats. The patients are list of patients that he/she treats. The patients are classified into three categories, according to their age. classified into three categories, according to their age. These categories include, child, adult, and senior. The These categories include, child, adult, and senior. The doctors are classified according to their specialization doctors are classified according to their specialization into the following categories: pediatrician, oncologist, into the following categories: pediatrician, oncologist, endocrinologist, and general practitioner. Each doctor endocrinologist, and general practitioner. Each doctor is assigned a dedicated administrative assistant who is is assigned a dedicated administrative assistant who is responsible for managing various functions such as responsible for managing various functions such as maintaining appointments, collecting payments etc. maintaining appointments, collecting payments etc. Draw a UML class diagram to model the information Draw a UML class diagram to model the information system for the doctor’s office.system for the doctor’s office.

Page 135: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

135

CSE

2102Common Design FlawsCommon Design Flaws

Classes that directly modify the private data of Classes that directly modify the private data of other classesother classes Provide operations in public interfaces Change private data only via operations

Item from HTSSItem from HTSS

Change RetailCost via UpdatePrice()Change RetailCost via UpdatePrice() Do not access RetailCost directlyDo not access RetailCost directly

class Item {class Item {

private: // Private Dataprivate: // Private Data

float RetailCost;float RetailCost;

public: // Public Methodspublic: // Public Methods

void UpdatePrice(float new_value);void UpdatePrice(float new_value);

};};

Page 136: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

136

CSE

2102Summary on DesignSummary on Design

We’ve Seen Wide Array of Design 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 Critical to Understand All of These Issues and More for Successful Software EngineeringMore for Successful Software Engineering

Page 137: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

137

CSE

2102An Overview of JavaAn Overview of Java

Java is a Third Generation, General Purpose, Java is a Third Generation, General Purpose, Platform Independent, Concurrent, Class-Based, Platform Independent, Concurrent, Class-Based, Object-Oriented Language and EnvironmentObject-Oriented Language and Environment

Java Composed of JDK and JREJava Composed of JDK and JRE Java LanguageJava Language Java Packages (Libraries)Java Packages (Libraries) javac Compiler to Bytecode (p-code)javac Compiler to Bytecode (p-code) JDB Java Debugger JDB Java Debugger Java Interpreter - Platform SpecificJava Interpreter - Platform Specific

JDK: Java Development EnvironmentJDK: Java Development Environment http://www.javasoft.com/products/jdk/1.2/http://www.javasoft.com/products/jdk/1.2/

JRE: Java Runtime EnvironmentJRE: Java Runtime Environment http://www.javasoft.com/products/jdk/1.2/jre/index.html

Page 138: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

138

CSE

2102Java and New Technologies (Mobile)Java and New Technologies (Mobile)

Page 139: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

139

CSE

2102Packages In JavaPackages In Java

Allows Related Classes to be Grouped into a Allows Related Classes to be Grouped into a Larger AbstractionLarger Abstraction Similar to Ada95 Packages Unavailable in C++

Utilization of Packages for SW Design and Utilization of Packages for SW Design and DevelopmentDevelopment Components, Modularization, Groupings Enforcement by Compiler of Package Rules

Overall, Packages Enhance the Control and Overall, Packages Enhance the Control and Visibility to Fine-Tune Visibility to Fine-Tune Who Can See What When

Page 140: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

140

CSE

2102The Java LanguageThe Java Language

Overview of Non-OO CapabilitiesOverview 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 JavaVariables in Java Primitive Types: ints, floats, booleans,

Unicode chars Reference Types: arrays, classes, interfaces

No Physical Pointers in Java!No Physical Pointers in Java!

Page 141: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

141

CSE

2102The Java LanguageThe Java Language

Statements in Java - Resembles C and C++Statements in Java - Resembles C and C++ Assignment/Expressions and Precedence for, while, do-while if-then, switch-case break, continue, label, return

Exception HandlingException Handling Similar to C++ try, throws, catch Blocks Strongly Integrated Throughout APIs

Page 142: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

142

CSE

2102

The Java LanguageThe Java LanguageMotivating the Class ConceptMotivating the Class Concept

Conceptually, Classes are Structures/Records Conceptually, Classes are Structures/Records with Functions that are Encapsulatedwith Functions that are Encapsulated

structure Item { int UPC, OnShelf, InStock, ROLimit; char* Name; float RCost, WCost;

Status Create_New_Item(int UPC, ...); NameCost* Get_Item_NameCost(int UPC); void Modify_Inventory(int UPC, int Delta) ; Boolean Check_If_On_Shelf(int UPC); Boolean Time_To_Reorder(int UPC); };

NameCost *nc;Item I1, I2;I1.Create_New_Item(...);nc = I2.Get_Item_NameCost(UPC);

Page 143: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

143

CSE

2102

The Java LanguageThe Java LanguageObject-Oriented FeaturesObject-Oriented Features

Class - similar to C++ ClassClass - similar to C++ Class Classes have Classes have MembersMembers ( (MethodsMethods and and VariablesVariables)) Members Tagged Using Members Tagged Using KeywordsKeywords

private: Typically, Inaccessible public: Potential to be Accessible protected: Accessible via Inheritance package: Accessible within Package

Involve Visible Between Classes, Within Involve Visible Between Classes, Within Packages, and Due to InheritancePackages, and Due to Inheritance

Page 144: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

144

CSE

2102Classes in JavaClasses in Java

A Supermarket ItemA Supermarket Item Keywords must be Utilized for Each Attribute Keywords must be Utilized for Each Attribute

or Method Declarationor Method Declaration

class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost;

public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta){...}; public int Get_InStock_Amt() {return Quantity;};};

Page 145: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

145

CSE

2102Classes in JavaClasses in Java

class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost;

public Item() { ... }; public void finalize() { ... }; public boolean 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(); {...};};

Page 146: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

146

CSE

2102Visibility of Attributes/MethodsVisibility of Attributes/Methods

Class Members (Attributes and Methods)Class Members (Attributes and Methods) Visibility Tags for MembersVisibility 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 Java's Controlled Sharing within/between Packages not Supported in C++not Supported in C++

Abstraction/Encapsulation Superior in Java!Abstraction/Encapsulation Superior in Java!

Page 147: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

147

CSE

2102Inheritance - Two RolesInheritance - Two Roles

Controlled Sharing Between ClassesControlled Sharing Between Classes Generalization vs. Specialization

Treat Instances of Different Classes in a Treat Instances of Different Classes in a Uniform FashionUniform Fashion Polymorphism and Dynamic Binding

Inheritance in JavaInheritance in Java

Item / \ DeliItem ProduceItem | SaladItem class DeliItem extends Item { ... };

class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... };

Page 148: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

148

CSE

2102Designing and Developing Java ClassesDesigning and Developing Java Classes

Encapsulation Capabilities of JavaEncapsulation Capabilities of Java Classes (Data + Operations) - ADTs Packages - Collections of “Related” Classes

Class Declaration:Class Declaration: Access Modes and Variable Members Constructors and Class Bodies Method Declaration and Access Modes Class and Instance Members Garbage Collection

Page 149: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

149

CSE

2102Class DefinitionClass Definition

public class Stack {public class Stack { private Vector items;private Vector items; public Stack() {public Stack() { items = new Vector(10);items = new Vector(10); }} public Stack(int numElem) {public Stack(int numElem) { items = new Vector(numElem);items = new Vector(numElem); }} public Object push(Object item) {public Object push(Object item) { item.addElement(item);item.addElement(item); return item;return item; }} public synchronized Object pop() {public synchronized Object pop() { int len = items.size();int len = items.size(); Object obj = null;Object obj = null; if (len == 0)if (len == 0) throw new EmptyStackException();throw new EmptyStackException(); obj = items.elementAt(len - 1);obj = items.elementAt(len - 1); items.removeElementAt(len - 1);items.removeElementAt(len - 1); return obj;return obj; }} public boolean isEmpty() {public boolean isEmpty() { if (items.size() == 0)if (items.size() == 0) return true;return true; elseelse return false;return false; }}}}

Class Body

Class DeclarationMemberVariable

Constructors

MemberMethods

Page 150: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

150

CSE

2102PackagesPackages

A A packagepackage is a Collection of Related Classes and is a Collection of Related Classes and Interfaces that Provides Access Protection and Interfaces that Provides Access Protection and Namespace ManagementNamespace Management

File Name and Package Name IdenticalFile Name and Package Name Identical Packages are Imported via the Packages are Imported via the importimport Keyword Keyword

package graphics;class Circle extend Graphic implements Draggable { ... }class Rectangle extends Graphic implements Draggable { ... }interface Draggable { ... }

Page 151: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

151

CSE

2102Access ModesAccess Modes

Constructors and Members Constructors and Members can be defined as: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 Controls Encapsulation and Allows Evolvability and Allows Evolvability with Minimal Impact on with Minimal Impact on other Classes that use the other Classes that use the MembersMembers

Deciding Appropriate Deciding Appropriate Access Mode Access Mode Determines Security and Determines Security and Ensures that Data Ensures that Data Remains in a Consistent Remains in a Consistent State.State.

Page 152: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

152

CSE

2102ConstructorsConstructors

Utilized to Create a new Class instance by Utilized to Create a new Class instance by Reserving Sspace for the Member Variables Reserving Sspace for the Member Variables Rectangle rect = Rectangle rect = newnew Rectangle(); Rectangle();

Member Variable Initialization PossibleMember Variable Initialization Possible Constructors Mimic Class Name with No Return Constructors Mimic Class Name with No Return

TypeType Default Constructor with Empty Argument ListDefault Constructor with Empty Argument List Constructors may be OverloadedConstructors may be Overloaded

Page 153: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

153

CSE

2102Variable MembersVariable Members

Declaration (Class Body)Declaration (Class Body) Defines the Type of a Variable

Instantiation (Constructor)Instantiation (Constructor) Reserves Memory for the New Instance

InitializationInitialization Assign Initial Value(s)

accessLevel Indicates the access level of this memberstatic Declares a class memberfinal Indicates that it is constanttransient This variable is transientvolatile This variable is volatiletype name The type and name of the variable

Page 154: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

154

CSE

2102Method MembersMethod Members

DeclarationDeclaration 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

Page 155: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

155

CSE

2102

accessLevel Access level for this methodstatic This is a class methodabstract This method is not implementedfinal Method cannot be overridennative Method implemented in another languagesynchronized Method requires a monitor to runreturnType methodName The return type and the method name(paramlist) The list of argumentsthrows exceptions The exceptions thrown by this method

Method Members (cont.)Method Members (cont.)

Page 156: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

156

CSE

2102ExampleExample

public class Point {public class Point { public int x = 0;public int x = 0; public int y = 0;public int y = 0;

public void move(int newX, int newY) {public void move(int newX, int newY) { x = newX;x = newX; y = newY;y = newY; }}}}

public class Line {public class Line { public Point origin;public Point origin; public Point end;public Point end;

public Line() {public Line() { origin = new Point();origin = new Point(); end = new Point();end = new Point(); }} public Line(Point origin, Point end) {public Line(Point origin, Point end) { this.origin = origin;this.origin = origin; this.end = end;this.end = end; }}}}

DefaultConstructor

Overloading

Hiding

origin end

x

y

x

y

aLineObject

LineInstance

PointInstances

Page 157: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

157

CSE

2102Class and Instance MembersClass and Instance Members

Class Members are Defined with the Keyword Class Members are Defined with the Keyword staticstatic

Class Variables and Class Methods are Associated Class Variables and Class Methods are Associated with the Class Rather than each of its Instanceswith the Class Rather than each of its Instances

Class Variables are Shared Among all InstancesClass Variables are Shared Among all Instances JRE Creates one copy of Class Variables the First JRE Creates one copy of Class Variables the First

Time it Encounters a Containing InstanceTime it Encounters a Containing Instance Class Methods only Operate on Class VariablesClass Methods only Operate on Class Variables Class Bariables declared as Class Bariables declared as finalfinal are constants are constants Class Members are Accessible without the need to Class Members are Accessible without the need to

Instantiate the ClassInstantiate the ClassclassName.classMethod();className.classVar = 10;

Page 158: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

158

CSE

2102Class and Instance Members (Continued)Class and Instance Members (Continued)

class AnInteger { int x; public int x() { return x; } public void setX(int 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());…

class AnInteger { int x; static public int x() { return x; } static public void setX(int

newX){ x = newX; }}

Page 159: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

159

CSE

2102Garbage CollectionGarbage Collection

Unreferenced Objects are Garbage Collected Unreferenced Objects are Garbage Collected AutomaticallyAutomatically

Memory is Freed for Later ReuseMemory is Freed for Later Reuse Garbage Collection runs in a Low Priority Thread, Garbage Collection runs in a Low Priority Thread,

either Synchronously or Asynchronouslyeither Synchronously or Asynchronously The The finalize()finalize() Method is Inherited from Method is Inherited from

ObjectObject and can be Overridden to Liberate and can be Overridden to Liberate ResourcesResources

Page 160: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

160

CSE

2102Inheritance in JavaInheritance in Java

Basic Definitions and ConceptsBasic Definitions and Concepts Generalization vs. Specialization Subclass vs. Superclass

Acquisition Rules 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 ClassesRole of Public, Final, and Abstract Classes Java Interfaces for Design-Level Multiple Java Interfaces for Design-Level Multiple

Inheritance and Quasi GenericsInheritance and Quasi Generics

Page 161: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

161

CSE

2102Inheritance - Terms and ConceptsInheritance - Terms and Concepts

Every Class in Java is Derived from the Object Every Class in Java is Derived from the Object ClassClass

Java Classes can be Organized into Hierarchies Java Classes can be Organized into Hierarchies Using the Using the extendsextends Keyword Keyword

Establishing Establishing Superclass/SubclassSuperclass/Subclass Relationships Relationships Between the Classes in ApplicationBetween the Classes in Application

A A SuperclassSuperclass Contains Members Common to Its Contains Members Common to Its SubclassesSubclasses - - GeneralizationGeneralization

SubclassesSubclasses Contain Members Different from Contain Members Different from Shared Shared SuperclassSuperclass - - SpecializationSpecialization

Only Single Inheritance is Supported in Java at Only Single Inheritance is Supported in Java at Implementation Level!Implementation Level!

Page 162: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

162

CSE

2102Subclass & SuperclassSubclass & Superclass

Subclass 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 oror hide the Inherited Member Variables and Override the Inherited Member Functions

SuperclassSuperclass Superclass is a Class’s Direct Ancestor

Page 163: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

163

CSE

2102A Superclass in JavaA Superclass in Java

A Supermarket ItemA Supermarket Item Keywords must be Utilized for Each Attribute Keywords must be Utilized for Each Attribute

or Method Declarationor Method Declaration

class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost;

public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta){...}; public int Get_InStock_Amt() {return Quantity;};};

Page 164: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

164

CSE

2102Inheritance - Defining Subclasses in JavaInheritance - Defining Subclasses in Java

ItemItem / \/ \ DeliItem ProduceItemDeliItem ProduceItem || SaladItemSaladItem

class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... };

Page 165: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

165

CSE

2102Members Inherited By a SubclassMembers Inherited By a Subclass

Subclass Inherits all Public/Protected Members Subclass Inherits all Public/Protected Members of a Superclassof a Superclass DeliItem Inherits Public/Protected from

Item Subclass Inherits all Package Members of Subclass Inherits all Package Members of

Classes in the same Package as the SubclassClasses in the same Package as the Subclass All superclass Members can be Declared with All superclass Members can be Declared with

no Access Specification, if Subclass is in the no Access Specification, if Subclass is in the Same Package as the SuperclassSame Package as the Superclass

Page 166: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

166

CSE

2102Members Not Inherited By A SubclassMembers Not Inherited By A Subclass

Subclass does not Inherit Private Members of a Subclass does not Inherit Private Members of a SuperclassSuperclass DeliItem doesn’t Inherit Private from Item

Subclasses do not Inherit a Superclass’s Member if Subclasses do not Inherit a Superclass’s Member if the Subclass Declares a Member with Same Namethe 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

Page 167: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

167

CSE

2102

Hiding Member Variables Hiding Member Variables and Overriding Member Methodsand 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)

}}

Page 168: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

168

CSE

2102Overriding Member MethodsOverriding Member Methods

Subclasses CANNOT Override Methods that are Subclasses CANNOT Override Methods that are Declared to be Final in the SuperclassDeclared to be Final in the Superclass

Subclasses MUST Override Methods that are Subclasses MUST Override Methods that are Declared as Abstract in the SuperclassDeclared as Abstract in the Superclass

Subclasses MUST be Declared as Abstract if they Subclasses MUST be Declared as Abstract if they do not Override Abstract Methods from the do not Override Abstract Methods from the SuperclassSuperclass

Page 169: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

169

CSE

2102Methods Inherited From Methods Inherited From ObjectObject Class Class

The Java “The Java “ObjectObject” Class Defines Basic State and ” Class Defines Basic State and Behavior of all Classes and Their InstancesBehavior of all Classes and Their Instances

User Defined Classes can Override these Methods:User Defined Classes can Override these Methods: clone equals finalize toString hashCode

User Defined Classes Cannot Override: User Defined Classes Cannot Override: getClass notify notifyAll wait

Page 170: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

170

CSE

2102Public, Final, and Abstract ClassesPublic, Final, and Abstract Classes

Public ClassesPublic Classes Within Package, public Classes Become

Visible to Outside World Public Members are Exported

Final ClassesFinal Classes Prohibits Subclassing for Security Final Class Prevents Access of Protected

Members via Subclassing Not Supported in C++/Ada95

Abstract ClassesAbstract Classes Can't be Instantiated No Implementations for Abstract Methods

Page 171: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

171

CSE

2102

Final Classes and Final Classes and the “Final” Keywordthe “Final” Keyword

A Class is Declared as Final - the Class Cannot be A Class is Declared as Final - the Class Cannot be Subclassed.Subclassed. For Security For Design

A Method is Declared as Final in a Class - any A Method is Declared as Final in a Class - any Subclass Cannot Override that MethodSubclass Cannot Override that Method

A Variable is Declared as Final - the Variable is a A Variable is Declared as Final - the Variable is a Constant and it Cannot be ChangedConstant and it Cannot be Changed

Page 172: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

172

CSE

2102Abstract Classes And MethodsAbstract Classes And Methods

Abstract ClassesAbstract 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 MethodsAbstract 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

Page 173: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

173

CSE

2102A Sample Abstract ClassA Sample Abstract Class

abstract class Item { protected String UPC, Name; protected int Quantity; protected double RetailCost, WholeCost;

public Item() { ... }; abstract public void finalize(); abstract public boolean Modify_Inventory(int Delta); public int Get_InStock_Amt() {...}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(double NewPrice);{...}; };

Page 174: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

174

CSE

2102Another Abstract Class and MethodsAnother 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() { . . . . . }

Page 175: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

175

CSE

2102Interfaces in JavaInterfaces in Java

Design-Level Multiple InheritanceDesign-Level Multiple Inheritance Java InterfaceJava Interface

Set of Methods (no Implementations) Set (Possibly Empty) of Constant Values

Interfaces Utilized Extensively Throughout Java Interfaces Utilized Extensively Throughout Java APIs to Acquire and Pass on FunctionalityAPIs 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

Page 176: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

176

CSE

2102A Sample Interface in JavaA Sample Interface in Java

Teaching

Student Employee / \ | UnderGrad Graduate 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

Page 177: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

177

CSE

2102Quasi Generics in JavaQuasi 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){ ... }}

Page 178: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

178

CSE

2102

Polymorphism and Polymorphism and Object Serialization in JavaObject Serialization in Java

PolymorphismPolymorphism 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! SerializationSerialization

Conversion of Object to Format that Facilitates Storage to File or Transfer Across Network

Process Controlled via API with Minimal Interaction by Software Engineer

Page 179: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

179

CSE

2102PolymorphismPolymorphism

SubstitutabilitySubstitutability 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 TypeStatic Type Type Defined in the Variable Declaration

Dynamic TypeDynamic Type Type of the Actual Value held by the Variable

at Runtime

Page 180: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

180

CSE

2102PolymorphismPolymorphism

A Variable is Polymorphic Whenever it may have A Variable is Polymorphic Whenever it may have Different Static and Dynamic TypesDifferent 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: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?

Page 181: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

181

CSE

2102An ExampleAn Example

We have a class We have a class BallBall, and , and two subclasses two subclasses WhiteBallWhiteBall and and BlackBallBlackBall

The The SelectOneSelectOne() method () method gets a gets a WhiteBallWhiteBall and a and a BlackBallBlackBall as arguments and as arguments and returns one of them returns one of them selected randomly selected randomly

Questions:Questions: What is SelectOne()’s

return type? How can we know

which ball was returned?

SelectOne

?

Page 182: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

182

CSE

2102Dynamic Binding and CastingDynamic 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"); }}

class balls {class balls { public static void main(String[] args) public static void main(String[] args)

{{ WhiteBall wb = new WhiteBall();WhiteBall wb = new WhiteBall(); BlackBall bb = new BlackBall();BlackBall bb = new BlackBall(); Ball b = SelectOne(wb, bb);Ball b = SelectOne(wb, bb); System.out.println(b.GetId());System.out.println(b.GetId()); System.out.println(b.id);System.out.println(b.id); if (b instanceof WhiteBall) {if (b instanceof WhiteBall) { wb = (WhiteBall)b;wb = (WhiteBall)b; wb.OnlyWhite();wb.OnlyWhite(); } else {} else { bb = (BlackBall)b;bb = (BlackBall)b; bb.OnlyBlack();bb.OnlyBlack(); }} }} public static Ball SelectOne(WhiteBall public static Ball SelectOne(WhiteBall

w, BlackBall b) {w, BlackBall b) { if (Math.random() > 0.5)if (Math.random() > 0.5) return w;return w; elseelse return b;return b; }}}}

The static type of b is Ball, but its dynamic type is either WhiteBallor BlackBall.

What is going to be printed?

Page 183: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

183

CSE

2102

Class Student (Superclass) - Maintains Class Student (Superclass) - Maintains Student InformationStudent 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 getName() { return name; }

public float getGpa() { return gpa; }

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); }}

Page 184: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

184

CSE

2102Class GradClass Grad

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); }}

Page 185: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

185

CSE

2102Class UndergradClass Undergrad

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(" advisor: " + advisor); System.out.println(" major: " + major); }}

Page 186: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

186

CSE

2102Class StudentDBClass 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; }

Page 187: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

187

CSE

2102Class StudentDB (Continued)Class StudentDB (Continued)

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)

stuList.removeElementAt(count - 1);

return stu; }

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(); } }}

Page 188: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

188

CSE

2102Class MainInterfaceClass 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: "); } }

Page 189: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

189

CSE

2102Class MainInterface (Continued)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); }

Page 190: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

190

CSE

2102Class MainInterface (Continued)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;

Page 191: 1 CSE 2102 Object-Oriented Design and Development Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut

191

CSE

2102Class MainInterface (Continued)Class MainInterface (Continued)

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(); } }}