Download presentation
Presentation is loading. Please wait.
Published byShanon Shepherd Modified over 9 years ago
1
Generic Classes Use Cases Inheritance
2
Generic Classes
3
The Scenario Imagine that you’ve just finished writing a wonderful NumberQueue class that works perfectly. But what about a Queue to hold strings? … or Booleans? … or user-defined records?
4
A Proper Balance Notice that in the process of creating the NumberQueue class… We’ve given too much information to the class (supplier). The algorithm (client) should specify what to hold. The Queue shouldn’t care about what it holds. The Queue should simply hold the items!
5
Achieving Proper Balance Hide details from the client –Using protected section of the class Keep certain information in the client –The object doesn’t / shouldn’t know about certain details Better abstraction and makes the class generic (more reusable)
6
A StudentCollection StudentCollection Initialize Add Remove Head IsEmpty RemoveHelper …
7
class StudentCollection public procedure Add(toAdd isoftype in Student) // contract comments here procedure Remove (toRemove isoftype in Student) // contract comments here function IsEmpty returnsa Boolean // contract comments here procedure Initialize // contract comments here protected ListNode definesa record data isoftype Student next isoftype ptr toa ListNode endrecord // ListNode Head isoftype ptr toa ListNode
8
// Still in the protected section procedure Add(toAdd isoftype in Student) temp isoftype ptr toa ListNode temp <- new(ListNode) temp^.data <- toAdd temp^.next <- Head Head <- temp endprocedure // Add function IsEmpty returnsa Boolean IsEmpty returns (Head = NIL) endfunction // IsEmpty procedure Initialize Head <- NIL endprocedure // Initialize
9
// Still in the protected section procedure Remove (toRemove isoftype in Student) RemoveHelper (Head, toRemove) endprocedure // Remove procedure RemoveHelper (current iot in/out ptr toa ListNode, toRemove isoftype in Student) if (current <> NIL) then if (current^.data = toRemove) then current <- current^.next else RemoveHelper(current^.next, toRemove) endif endprocedure // RemoveHelper endclass // StudentCollection
10
Other Collections What about other collections? –String –Num –Etc. Maintaining multiple classes would be counterproductive.
11
class StudentCollection public procedure Add(toAdd isoftype in Student) // contract comments here procedure Remove (toRemove isoftype in Student) // contract comments here function IsEmpty returnsa Boolean // contract comments here procedure Initialize // contract comments here protected ListNode definesa record data isoftype Student next isoftype ptr toa ListNode endrecord // ListNode Head isoftype ptr toa ListNode
12
// Still in the protected section procedure Add(toAdd isoftype in Student) temp isoftype ptr toa ListNode temp <- new(ListNode) temp^.data <- toAdd temp^.next <- Head Head <- temp endprocedure // Add function IsEmpty returnsa Boolean IsEmpty returns (Head = NIL) endfunction // IsEmpty procedure Initialize Head <- NIL endprocedure // Initialize
13
// Still in the protected section procedure Remove (toRemove isoftype in Student) RemoveHelper (Head, toRemove) endprocedure // Remove procedure RemoveHelper (current iot in/out ptr toa ListNode, toRemove isoftype in Student) if (current <> NIL) then if (current^.data = toRemove) then current <- current^.next else RemoveHelper(current^.next, toRemove) endif endprocedure // RemoveHelper endclass // StudentCollection
14
Better Abstraction Why not let the class worry only about managing the items? It should have no concept of what it’s holding. This will dramatically increase reusability. Why not specify the type of items to hold via a parameter?
15
A Collection Collection Initialize Add Remove Head IsEmpty RemoveHelper …
16
Making the Class Generic Instead of a specific data type to hold, declare a “magic word” on which we’ll later search and replace. When the class is instantiated later into an object, then specify the desired type. Use a parameter to the class definition and instantiation.
17
class Collection (DataType) public procedure Add(toAdd isoftype in DataType) // contract comments here procedure Remove (toRemove iot in DataType) // contract comments here function IsEmpty returnsa Boolean // contract comments here procedure Initialize // contract comments here protected ListNode definesa record data isoftype DataType next isoftype ptr toa ListNode endrecord // ListNode Head isoftype ptr toa ListNode
18
// Still in the protected section procedure Add(toAdd isoftype in DataType) temp isoftype ptr toa ListNode temp <- new(ListNode) temp^.data <- toAdd temp^.next <- Head Head <- temp endprocedure // Add function IsEmpty returnsa Boolean IsEmpty returns (Head = NIL) endfunction // IsEmpty procedure Initialize Head <- NIL endprocedure // Initialize
19
// Still in the protected section procedure Remove (toRemove iot in DataType) RemoveHelper (Head, toRemove) endprocedure // Remove procedure RemoveHelper (current iot in/out ptr toa ListNode, toRemove iot in DataType) if (current <> NIL) then if (current^.data = toRemove) then current <- current^.next else RemoveHelper(current^.next, toRemove) endif endprocedure // RemoveHelper endclass // Collection
20
Instantiating Generic Classes Simply add a type as a parameter to the declaration of the object: Algorithm CollectionExample uses Collection Students isoftype Collection(Student) WordList isoftype Collection(String) Numbers isoftype Collection(Num)
21
Using Objects of Generic Classes Just as before: algorithm CollectionExample... Numbers.Add(42) Numbers.Add(31) Numbers.Remove(42) if (Numbers.IsEmpty) then print(“Empty collection of numbers”) endif WordList.Add(“CS is fun!”)...
22
Summary Everything in its proper place –Hide details from the client in the protected section –Hide details from the class using generic parameters This gives better abstraction and increases reusability.
23
Questions?
24
Use Cases
25
Designing an OO Solution Ask yourself, “What are the characteristics of the system I want to model?” Use natural language to describe scenarios, or cases of use. Natural language descriptions define how each user of a system intends to use it.
26
Use Cases Frequently causes you to think more clearly about the system design “before it’s too late.” Useful in providing introduction to the system requirements: –Identify users –Identify major system components (classes) –Identify methods and attributes needed for each component
27
Use Case Design From the use case scenarios, we can construct our classes with methods and attributes: –Nouns become classes or attributes –Verbs become methods
28
Use Case Example A passenger wishing to go to another floor of the building presses the elevator call button. When an elevator is available, the doors open and the passenger enters the cage. The passenger presses one of the inside buttons to select the destination floor. The doors close and the elevator moves to the destination floor; the doors open and the passenger leaves. When an elevator requires maintenance, the maintainer disables the elevator call buttons, attaches his external control box and exercises individual elevator control commands and display features.
29
Visual Diagram of A System Lobby Doors Passenger Elevator #1 Passenger Elevator #2 Passenger Elevator #3 Service Elevator
30
Relationships between Classes: “Has-a” Elevator Open Doors Close Doors Move to Floor Identity Weight Doors People Position Door Open Close Identity Weight Color Position
31
Relationships between Classes: “Is-A” Elevator Open Doors Close Doors Thing Move Open Close Door
32
Issues What are the main tasks to be performed by each actor? (Class definition) What could go wrong with each task? (Fault tolerance and recovery) What information is required for each task, produced by it, or changed by it? (Information and method passing)
33
Issues Do the actors have to be involved by providing input about the external world? (Interface) What information does the actor desire from the system? (User-centered design) Should the actor be informed of unexpected events or unavailable equipment or capabilities? (Visibility)
34
Questions?
35
Inheritance
36
Relationships Between Classes Has-A –One class can provide services to another, acting as an attribute Is-A –One class inherits the abilities of another class
37
Elevator Instances Lobby Doors Passenger Elevator #1 Passenger Elevator #2 Passenger Elevator #3 Service Elevator
38
Relationships between Classes: Using - “Has-A” Elevator Open Doors Close Doors Move to Floor Identity Color State Doors Position Door Open Close Identity State Color IsOpen “Has-A”
39
Relationships between Classes: Being - “Is-A” Elevator Open Doors Close Doors Position Doors Door Open Close IsOpen Thing Move Identity Color State “Is-A”
40
Defining the Differences Classes often share capabilities We want to avoid re-coding these capabilities Re-use of these would be best to –Improves maintainability –Reduces cost –Improves “real world” modeling
41
Inheritance Defined When one class re-uses the capabilities defined in another class. The new subclass gains all the methods and attributes of the superclass. Superclass Subclass Thing ElevatorDoor
42
Inheritance Example Elevator Open Doors Close Doors Position Doors Door Open Close IsOpen Thing Move Identity Color State
43
Benefits of Inheritance Saves effort of “reinventing the wheel” Allows us to build on existing code, specializing without having to copy it, rewrite it, etc. To create the subclass, we need to program only the differences between the superclass and the subclass that inherits from it. Allows for flexibility in class definitions.
44
Inheriting from a SuperClass class inherits public protected endclass //
45
Two Types of Inheritance Extension –Adds attributes and methods Redefinition –Changes/modifies existing methods, specializing as needed
46
Inheritance Examples Given a bank account class… Extension –Add the capability of calculating interest Redefinition –Redefine how withdraws occur
47
Consider a primitive bank account which allows only three kinds of transactions: – Deposits – Withdrawals – Ability to check current balance Inheritance Example: Bank Accounts
48
The Base Class Bank_Account Bank_Account balance Deposit Withdraw Initialize Get_Balance
49
A Superclass Bank_Account class Bank_Account public procedure Deposit (amt isoftype in Num) // comments here procedure Withdraw(amt isoftype in/out Num) // only allows withdraw up to current balance function Get_Balance returnsa Num // comments here procedure Initialize // comments here protected balance isoftype Num procedure Deposit (amt isoftype in Num) balance <- balance + amt endprocedure // Deposit
50
A Base Class (cont’d) //still in protected section procedure Withdraw(amt isoftype in/out Num) if (balance < amt) then amt <- balance endif balance <- balance - amt endprocedure // Withdraw function Get_Balance returnsa Num Get_Balance returns balance endfunction // Get_Balance procedure Initialize balance <- 0 endprocedure // Initialize endclass // Bank_Account
51
Inheritance by Extension Imagine that we wish to create a new kind of Bank Account that is: –Identical to the base class in all respects, except one –We want to add the ability for the account to earn interest Without inheritance, we’d have to write it from scratch, duplicating code, etc. With inheritance, we need code only the new capability and inherit the rest.
52
Illustration of Inheritance Bank_Account balance Deposit Withdraw Initialize Get_Balance Savings_Account RATE MIN_BALANCE Calc_Interest // protected section Function Calc_Interest... endfunction
53
Inheritance by Extension class Savings_Account inherits Bank_Account public // inherits Deposit, Withdraw, Get_Balance function Calc_Interest returnsa Num // comments here protected // inherits balance RATE is.023 // 2.3% MIN_BALANCE is 500
54
Inheritance by Extension (cont’d) // still in protected section function Calc_Interest returnsa Num if (balance >= MIN_BALANCE) then Calc_Interest returns balance * RATE else Calc_Interest returns 0 endif endfunction // Calc_Interest endclass // Savings_Account
55
Using Subclasses in Algorithms algorithm BankExample uses Savings_Account my_savings isoftype Savings_Account my_savings.Initialize // superclass method... my_savings.Deposit(500) // superclass method my_interest isoftype Num my_interest <- my_savings.Calc_Interest // subclass method... my_savings.Withdraw(amount) // superclass method endalgorithm // BankExample
56
Inheritance by Redefinition Imagine that we wish to create a new kind of Savings Account that is: –identical to Savings Account in all respects, except one: we want to change the way in which withdrawals are handled the base class already handles withdrawals, but now we want a subclass that does them differently. Without inheritance, we’d have to rewrite it from scratch. With inheritance, we need code only the new way that we want withdrawals to work,
57
Illustration of Redefinition Savings_Account RATE MIN_BALANCE Calc_Interest Cool_Savings overdraft_ok OVERDRAFT_CHARGE Allow_Overdraft // protected section procedure Withdraw... procedure Initialize...
58
Inheritance by Redefinition class Cool_Savings inherits Savings_Account public procedure Allow_Overdraft(ok iot in Boolean) // new method: extending superclass protected overdraft_ok isoftype Boolean // extension OVERDRAFT_CHARGE is 20 // extension procedure Allow_Overdraft(ok iot in Boolean) overdraft_ok <- ok endprocedure // Allow_Overdraft
59
// still in protected section procedure Withdraw(amt isoftype in/out Num) if (overdraft_ok) then balance <- balance - amt if (balance < 0) then balance <- balance – OVERDRAFT_CHARGE endif else Super.Withdraw(amt) // calls super version endif endprocedure // Withdraw procedure Initialize // redefines Init. Super.Initialize // uses super method overdraft_ok <- FALSE // and adds to it. endprocedure // Initialize endclass // Cool_Savings Inheritance and Redefinition (cont’d)
60
Super “Super” is a built-in attribute to all classes which inherit from another class. “Super” allows us to access the implementation of a method in the superclass. For example, Super.Initialize executes the Initialize implementation in the superclass of the class.
61
Using Subclasses in Algorithms my_cool_savings isoftype Cool_Savings my_cool_savings.Initialize // both my_cool_savings.Deposit(250) // super method... my_cool_savings.Withdraw(amount) // both // check amount to see if correctly done my_cool_savings.Allow_Overdraft(TRUE) // subclass method my_interest isoftype Num my_interest <- my_cool_savings.Calc_Interest // super method... my_cool_savings.Withdraw(amount)// subclass method
62
Summary of Inheritance Extension take a base class and add new capabilities to it (methods, attributes). Redefinition take a base class and redefine an existing method, implement it in a new way in order to change capability or performance. Both allow us to code only the differences.
63
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.