Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Object-Oriented Programming and the Java Programming Language.

Similar presentations


Presentation on theme: "Introduction to Object-Oriented Programming and the Java Programming Language."— Presentation transcript:

1

2 Introduction to Object-Oriented Programming and the Java Programming Language

3 Session 1: Introduction to Object-Oriented Programming Objects, Messages And Classes

4 Session 1: Overview O-O Roadmap –Basic Concepts and Vocabulary (OOP-speak) –Objects in an Executing Program Kindergarten Object-Oriented Design –Stock Portfolio Problem –Vending Machine Problem

5 Characteristics of OOP Programming as modeling The model elements are called objects An executing program is a collection of objects

6 In Object-Oriented Programming... Objects are the active elements in the program. Not: “the computer does …” Rather: “the object does …”

7 Objects and Messages Objects are activated by messages Objects act by sending messages Senders and receivers

8 What's In A Message? Name of Desired Behavior print (method name) Additional Information “Hello world” (arguments) print(“Hello world”)

9 What's In An Object? Code To Implement Various Behaviors (methods) push, pop, isEmpty withdraw, deposit, getBalance Internal State (variables) arr, top accountNum, owner, balance, dateOpened

10 Messages and Methods An Object (receiver) method1 argumentN argument1 A Message: Method name + arguments method1 method2 method3 method4 An Object (sender)

11 When An Object Recieves A Message An Object (receiver) method1 method2 method3 method4 An Object (sender) Returned object method2 argumentN argument1 message

12 Behavior Behavior: what an object does Determined by object's methods Instigated by receipt of message Object (receiver) method1 method2 method1 argumentN argument1 …

13 Prototype Syntactic Description of –Message Method name Arguments accompanying objects in the message –Message result an object that is returned to the sender

14 Interface Collection of prototypes Interface of object: prototypes of the object's methods (Java uses the term interface for a related but more language-specific concept)

15 Classes Class— a repository of behavior Object: an instance of a class Object’s behavior defined by its class Instances of the same class share behavior

16 State Variables internal to object— instance variables Modifies behavior of objects of the same class –Example: 2 Name objects w/ a getFirst method Instances of the same class –Share behavior –Differ in state Generally hidden, invisible

17 Instances and State Name Gerry Weiss Joe Thurm Jackie Jones get first add title get first Jackie get first Joe get first Yudy get first

18 Object Creation (I) The Creation Problem: The object does not exist yet— can’t send it a message Possible Solutions? –Implicit or explicit message to class (as if the class were an object!) –Special creator object Not a real problem, just metaphysical!

19 Object Initialization Who should take responsibility for initializing an object’s state upon creation? THE OBJECT ITSELF OF COURSE!

20 Constructors special methods of the object invoked during creation only

21 Object Creation: Summary Creating Object constructor SomeClas s New Object method1 constructor methodN SomeClas s New Object method1 constructor methodN

22 Program Initiation Similar to the Object Creation Problem –if no objects exist at the start, how does anything happen? One Initiation Myth: –Special application object –External entity sends it a start message invoking a start method Not a real problem, just metaphysical!

23 Imperative Programming— Gone? Lives in modified form in method definitions –assignment –control structures –message-sending –non-object data types (language dependent)

24 Imperative Programming Under OOP: The object, not the computer, is the actor minor point perhaps? (I don’t think so!)

25 O-O vs Procedural Programming (I) Procedural: –if you want something done find a procedure and call it –If no procedure exists, write one

26 O-O vs Procedural Programming (II) OOP: –If you want something done find an object and send it a message –If no object exists, find a class and create an instance –If no class exists, write a class definition

27 O-O vs Procedural Programming (III) Procedural programmer spends life writing procedures O-O programmer spends life writing class definitions

28 Example: Payroll Purpose: Picture the object-creation, message-passing interplay of objects in an executing program. Statement of The Problem: Given a source of time card information and a personnel file, print payroll checks

29 What Objects Would You Expect? Statement of The Problem (again): Given a source of time card information and a personnel file, print payroll checks Common heuristic: look for the nouns.

30 Payroll Classes PayrollMaster Employee PersonnelFile TimeCard TimeCardFile Check SS# Hours

31 Payroll Objects TimeCard getSS getTime TimeCard File getCard Payroll Master DoPayroll Personnel File lookup SS match Time getHours Employee PayYourself Check print Program main

32 TimeCard File getCard Payroll Master DoPayroll Payroll Master DoPayroll Personnel File lookup TimeCard File getCard Payroll Program (1) Program main Payroll Master DoPayroll Personnel File lookup Personnel File lookup TimeCard File getCard

33 TimeCard File getCard Payroll Master DoPayroll Personnel File lookup TimeCard getSS getTime TimeCard getSS getTime TimeCard getSS getTime PayrollMaster: DoPayroll (1)

34 TimeCard getSS getTime TimeCard File getCard Payroll Master DoPayroll Personnel File lookup get SS SS match SS match get SS SS match get SS PayrollMaster: DoPayroll (2) get SS SS match

35 get Time Time getHours get Time Time getHours PayrollMaster: DoPayroll (3) TimeCard getSS getTime TimeCard File getCard Payroll Master DoPayroll Personnel File lookup SS match get Time Time getHours Time getHours Time getHours

36 Personnel: Lookup TimeCard getSS getTime TimeCard File getCard Payroll Master DoPayroll Personnel File lookup SS match Time getHours Employee PayYourself Employee PayYourself Employee PayYourself

37 PayrollMaster: DoPayroll (4) TimeCard getSS getTime TimeCard File getCard Payroll Master DoPayroll Personnel File lookup SS match Time getHours Employee PayYourself Check print Check print Check print Check print Check print Check print

38 Payroll Program (2) TimeCard getSS getTime TimeCard File getCard Payroll Master DoPayroll Personnel File lookup SS match Time getHours Employee PayYourself Check print Program main

39 A Peculiar Employee Design? Since when do employees create their own checks? Since when are employees trusted to determine their own pay? (not in OUR contract!) SMART and HELPFUL Objects

40 BREAK! Coming Up: Object-Oriented Design

41 OOP and O-O Design Can't rush in and “program” Design phase needed even in simple problems –desirable in procedural programming –sine qua non in O-O world O-O design methodologies: –numerous –we'll consider just one simple one

42 Kindergarten OOD Statement of Problem Possible Objects Primary Object Behavior Interface Sample Use Implement

43 Kindergarten OOD Not appropriate for all problems Works surprisingly well on many –great for CS1 Illustrate with an example: Find the value of a portfolio of stocks based on “ticker-tape” information

44 Statement of Problem: Find the value of a portfolio of stocks based on "ticker-tape" information.

45 Possible Objects: Portfolio Holding (a portfolio item) Value TickerTape

46 Primary Object? not Holding not Value Portfolio vs. TickerTape?

47 Both primary in the sense of independence But to which object should we send a message to solve our problem?

48 Is Portfolio the Primary Object? If so, Portfolio has this behavior: get Value of Portfolio, given TickerTape

49 Is TickerTape the Primary Object? If so, TickerTape has this behavior: –get Value of Portfolio, given Portfolio Should TickerTape be responsible for computing the Value of a Portfolio?

50 Responsibility-Driven Design: objects should be responsible for themselves example: –objects should be responsible for their own initialization (constructors) TickerTape should not be responsible for Value of a Portfolio, Portfolio should Primary Object: Portfolio

51 Behavior of Portfolio: get Value, given TickerTape constructor, given a file listing of a portfolio

52 Interface of Portfolio: class Portfolio { Portfolio create() Value getValue(TickerTape t) }

53 Sample Use: create TickerTape t create Portfolio p to p: get Value v, given t to v: print

54 Implementing Portfolio: class Portfolio { constructor() { } Value getValue(TickerTape t) { } }

55 Implementing Portfolio: getValue (1): class Portfolio { Value getValue(TickerTape t) { for each Holding h in Collection c of Holdings { get the Value of h increase the total by v } return total } } Needed: STATE: Collection object, c A Portfolio HAS-A collection of holdings Local Value object, total

56 Implementing Portfolio: getValue (2): class Portfolio { Value getValue(TickerTape t) { Value total initialized to 0 for each Holding h in Collection c of Holdings { get the Value of h increase the total by v } return total } STATE: Collection c }

57 Getting The Value of a Holding (1) This is OOP Ya want something done, send an object a message to h: getValue

58 Getting The Value of a Holding (2) to h: getValue Problem: a Holding is responsible for name of stock number of shares NOT current market value Solution: send h an object that has the necessary behavior to h: getValue given TickerTape t

59 Increasing a Value This is OOP Ya want something done, send an object a message to total: increase by...

60 Implementing Portfolio: getValue (3): class Portfolio { Value getValue(TickerTape t) { Value total initialized to 0 for each Holding h in Collection c of Holdings { to h: get the Value v of your stock, given t to total: increase by v } return total } STATE: Collection c } Remark: Who initializes the Collection?

61 The Portfolio Constructor (1) class Portfolio { constructor() { create Collection c... ??? }... STATE: Collection c }

62 Constructor Questions and Answers Questions: –where will the portfolio data come from? – in what form will it be? Answers (let's say): – from a TokenSource –a sequence of (stock name and number) pairs Question: –Where should the responbility for creating TokenSource lie?

63 The Portfolio Constructor (2) class Portfolio { constructor(TokenSource src) { create Collection c create Holding h, given src while h was created successfully { to c: add h create Holding h, given src } } … STATE: Collection c }

64 Portfolio Class: class Portfolio { constructor(TokenSource src) { create Collection c create Holding h, given src while h was created successfully { to c: add h create Holding h, given src } } Value getValue(TickerTape t) { Value total initialized to 0 for each Holding h in Collection c of Holdings { to h: get the Value v of your stock, given t to total: increase by v } return total } STATE: Collection c }

65 Class Summary Completed: –Portfolio Yet To Complete: –TickerTape –TokenSource –Collection –Holding –Value

66 Details of Remaining Classes: TickerTape— constructor TokenSource — constructor get String Collection— constructor add... some way of iterating … Holding— constructor, given TokenSource get Value given TickerTape Value— constructor, given an integer value increase, given a Value print

67 NEXT STEP: Pick a class and follow same procedure… TickerTape TokenSource Collection Holding Value

68 Statement of SubProblem… … skip steps because behavior interface have been determined

69 Behavior of Holding: create, given TokenSource get Value given TickerTape

70 Interface of Holding: class Holding { constructor(TokenSource src) Value getValue(TickerTape t) }

71 Sample Use:... from implementation of Portfolio

72 Implementing Holding: class Holding { constructor(TokenSource src) { } Value getValue(TickerTape t) } }

73 Implementing Holding: getValue class Holding { Value getValue(TickerTape t) { to t: get Value v of stock named by my StockName to v: multiply by my Number return v } } Remarks: –the object must maintain a StockName and a Number, call them sn and n

74 Implementing Holding: STATE class Holding { Value getValue(TickerTape t) { to t: get Value v given sn to v: multiply by n return v } STATE:StockName sn Number n }

75 Implementing Holding: constructor class Holding { constructor(TokenSource src) { create StockName sn, given src create Number n, given src }... STATE:StockName sn Number n } Remark: Each class bears the responsibility for doing most of the work to create its own instances

76 The Holding Class class Holding { constructor(TokenSource src) { create StockName sn, given src create Number n, given src } Value getValue(TickerTape t) { to t: get Value v given sn to v: multiply by n return v } STATE:StockName sn Number n }

77 Class Summary Completed: –Portfolio –Holding Yet To Complete: –TickerTape –TokenSource –Collection –Value –Number –StockName

78 Details of Remaining Classes (I): TickerTape— constructor –get Value given a StockName TokenSource — constructor –get String Collection— constructor –add –... some way of iterating … NEW!

79 Details of Remaining Classes (II): Value— constructor, given an integer value –increase, given a Value –multiply, given a Number –print Number— constructor StockName— constructor NEW!

80 NEXT STEP: Pick a class and follow procedure.... TickerTape TokenSource Collection Value Number StockName

81 Statement of SubProblem:... skip steps because behavior, interface has been determined

82 Behavior of TickerTape: Create get Value given StockName

83 Interface of TickerTape: class TickerTape { constructor() TickerTape getValue(StockName sn) }

84 Sample Use:... from implementation of Holding

85 Implementing TickerTape class TickerTape { constructor() { } Value getValue(StockName sn) { } }

86 Implementing TickerTape: getValue Remark: need a Collection in my state class TickerTape { Value getValue(StockName sn) { for each StockQuote s in my Collection c of StockQuotes { to s: does sn match? if yes { to s: getValue v return v } } error } }

87 Implementing TickerTape: State class TickerTape { Value getValue(StockName sn) { for each StockQuote s in my Collection c of StockQuotes { to s: does sn match? if yes { to s: getValue v return v } } error } STATE:Collection c }

88 Implementing TickerTape: constructor class TickerTape { constructor(TokenSource src) { create Collection c create StockQuote s given src while not failure { to c: add s create StockQuote s given src } }... STATE:Collection c }

89 The TickerTape Class class TickerTape { constructor(TokenSource src) { create Collection c create StockQuote s given src while not failure { to c: add s create StockQuote s given src } }

90 The TickerTape Class (continued) Value getValue(StockName sn) { for each StockQuote s in my Collection c of StockQuotes { to s: does sn match? if yes { to s: getValue v return v } } error } STATE:Collection c }

91 Class Summary Completed: –Portfolio –Holding –TickerTape Yet To Complete: –TokenSource –Collection –Value –Number –StockName –StockQuote

92 Details of Remaining Classes (I): TokenSource — constructor –get String Collection— constructor –add –... some way of iterating … Value— constructor, given an integer value –increase, given a Value –multiply, given a Number –print

93 Details of Remaining Classes (II): Number— constructor StockName— constructor StockQuote— constructor, given a TokenSource –match a StockName –return the Value of a stock NEW!

94 NEXT STEP: Pick a class and follow procedure.... TickerTape TokenSource Collection Value Number StockName StockQuote

95 Statement of SubProblem:... skip steps because behavior, interface has been determined

96 Behavior of StockQuote: create, given a TokenSource get Value is match? given a StockName

97 Interface of StockQuote: class StockQuote { constructor(TokenSource src) Value getValue() boolean isMatch(StockName sn) }

98 Sample Use:... from implementation of TickerTape

99 Implementing StockQuote class StockQuote { constructor(TokenSource src) { } StockQuote getValue() { } boolean isMatch(StockName sn) { }

100 Implementing StockQuote (I) class StockQuote { constructor(TokenSource src) { } StockQuote getValue() { return v; } boolean isMatch(StockName sn) { to sn: does my StockName sn match? if yes return true else return false } STATE:Value v StockName sn }

101 Implementing StockQuote (II) class StockQuote { constructor(TokenSource src) { create StockName sn, given src create Value v, given src }... STATE:Value v StockName sn }

102 The StockQuote Class class StockQuote { constructor(TokenSource src) { create StockName sn, given src create Value v, given src } StockQuote getValue() { return v; } boolean isMatch(StockName sn) { to sn: does my StockName sn match? if yes return true else return false } STATE:Value v StockName sn }

103 Class Summary Completed: –Portfolio –Holding –TickerTape –StockQuote Yet To Complete: –TokenSource –Collection –Value –Number –StockName

104 Details of Remaining Classes (I): TokenSource — constructor –get String Collection— constructor –add –... some way of iterating … Value— constructor, given an integer value –increase, given a Value –multiply, given a Number –print

105 Details of Remaining Classes (II): Number— constructor StockName— constructor –is Match? given another StockName NEW!

106 NEXT STEP: Pick a class and follow procedure.... TickerTape TokenSource Collection Value Number StockName

107 Statement of SubProblem:... skip steps because behavior, interface has been determined

108 Behavior of Value: create, given a TokenSource increase, given a Value multiply, given a Number print

109 Interface of Value: class Value { Value create(TokenSource src) void increase(Value v) void multiply(Number n) void print() }

110 Sample Use:... from implementation of TickerTape

111 Implementing Value class Value { Value create(TokenSource src) { } void increase(Value v) { } void multiply(Number n) { } void print() { } }

112 Implementing Value: constructor class Value { constructor(TokenSource src) { to src: get String integerPart to src: get String fraction to fraction: contains / ? if no to src: put back String fraction // just use integerPart else // use integerPart and fraction }... }

113 Implementing Value: other methods class Value { Value create(TokenSource src) {... } void increase(Value v) { // defer } void multiply(Number n) { // defer } void print() { // defer } STATE: ??? }

114 Class Summary Completed: –Portfolio –Holding –TickerTape –StockQuote –Value (partially) Yet To Complete: –TokenSource –Collection –Number –StockName

115 Details of Remaining Classes: TokenSource — constructor –get String –put back String, given String Collection— constructor –add –... some way of iterating … Number— constructor StockName— constructor –is Match? given another StockName NEW!

116 NEXT STEP: And so on … (I'm tired now— aren't you?)

117 A Vending Machine

118 The Objects Vending Machine Merchandise Coins Selection Buttons Coin Return Lever Coin Return Slot Prices Quantities

119 Wait, There’s More! Vending machines model two aspects –The user interface (front panel) –The internal processing

120 Wait, There’s More! (II) Vending processor –verifies price –verifies item availability –verified change availability –makes change

121 Why Bother? Different machines, same processing A1 B2 C3 Please speak your selection into the grill Enter action: insert 5 Enter action: select 3 coins only Enter bill Enter card One application, many interfaces

122 The Objects (II) Vending Machine Vending Processor Merchandise Coins Selection Buttons Coin Return Lever Coin Return Slot Prices Quantities

123 Beginning the Design Primary objects –Vending processor –Vending machine The processor behavior is the one we were really interested in –Besides, a really snazzy machine interface is beyond us (for the moment)

124 Beginning the Design (II) We will design from the user’s perspective only The implementation will be done later

125 Behavior of Vending Processor create prices/quantities are specified for the locations –Actual item is of no interest the amount of change is specified coins are inserted the coin return is pressed a selection is made

126 Interface for Vending Processor constructor fill(Number selection, Price price, Number quantity) fill(Change c) insertCoin(Coin c) Change returnCoins() Change makeSelection(Number selection) makeSelection must also indicate success Vending Machine constructor fill/fill insertCoin returnCoins makeSelection

127 Behavior of Change create coins are added coins are removed a query is made for the number of coins of a particular denomination Who makes change? (responsibility again)

128 Behavior of Change (Improved) create coins are added change is made my total value is queried I am emptied Notice first person usage

129 Interface for Change constructor(Number nickels, Number quarters) Number add(Coin c) Change makeChange(Number amount) Number getValue() Change empty() We will assume nickels and quarters only Change constructor add makeChange getValue empty

130 The Behavior of Coin create value is queried Also somewhat thin What about allowing ‘nickel’ or ‘quarter’ for creation or printing?

131 Interface for Coin constructor(Number value) constructor(String description) Number getValue() String toString() Not so thin anymore Coin constructor getValue toString

132 Behavior of Vending Machine create start the machine This is just my design for a machine, plenty of others

133 Interface for Vending Machine constructor() startup() VendingMachine constructor startup

134 How About … ? disburse actual food display instructions interact with Vending Processor object These will all be present when we implement the class –They’re just not part of the user’s view

135 Class Summary Change constructor add makeChange getValue empty VendingProcessor constructor fill/fill insertCoin returnCoins makeSelection Coin constructor getValue toString VendingMachine constructor startup

136 A Vending Machine An Example of an Embedded System

137 A Vending Machine

138 The Objects Vending Machine Merchandise Coins Selection Buttons Coin Return Lever Coin Return Slot Prices Quantities

139 Wait, There’s More! Vending machines model two aspects –The user interface (front panel) –The internal processing

140 Wait, There’s More! (II) Vending processor –verifies price –verifies item availability –verified change availability –makes change

141 Why Bother? Different machines, same processing A1 B2 C3 Please speak your selection into the grill Enter action: insert 5 Enter action: select 3 coins only Enter bill Enter card One application, many interfaces

142 The Objects (II) Vending Machine Vending Processor Merchandise Coins Selection Buttons Coin Return Lever Coin Return Slot Prices Quantities

143 Beginning the Design Primary objects –Vending processor –Vending machine The processor behavior is the one we were really interested in –Besides, a really snazzy machine interface is beyond us (for the moment)

144 Beginning the Design (II) We will design from the user’s perspective only The implementation will be done later

145 Behavior of Vending Processor create prices/quantities are specified for the locations –Actual item is of no interest the amount of change is specified coins are inserted the coin return is pressed a selection is made

146 Interface for Vending Processor constructor fill(Number selection, Price price, Number quantity) fill(Change c) insertCoin(Coin c) Change returnCoins() Change makeSelection(Number selection) +makeSelection must also indicate success Vending Machine constructor() fill/fill() insertCoin() returnCoins() makeSelection()

147 Behavior of Change create coins are added coins are removed a query is made for the number of coins of a particular denomination +Who makes change? (responsibility again)

148 Behavior of Change (Improved) create coins are added change is made my total value is queried I am emptied +Notice first person usage

149 Interface for Change constructor(Number nickels, Number quarters) Number add(Coin c) Change makeChange(Number amount) Number getValue() Change empty() We will assume nickels and quarters only Change constructor() add() makeChange() getValue() empty()

150 The Behavior of Coin create value is queried +Also somewhat thin +What about allowing ‘nickel’ or ‘quarter’ for creation or printing?

151 Interface for Coin constructor(Number value) constructor(String description) Number getValue() String toString() +Not so thin anymore Coin constructor() getValue() toString()

152 Behavior of Vending Machine create start the machine +This is just my design for a machine, plenty of others

153 Interface for Vending Machine constructor() startup() VendingMachine constructor() startup()

154 How About … ? disburse actual food display instructions interact with Vending Processor object These will all be present when we implement the class –They’re just not part of the user’s view

155 Class Summary Change constructor() add() makeChange() getValue() empty() VendingProcessor constructor() fill/fill() insertCoin() returnCoins() makeSelection() Coin constructor() getValue() toString() VendingMachine constructor() startup()


Download ppt "Introduction to Object-Oriented Programming and the Java Programming Language."

Similar presentations


Ads by Google