Presentation is loading. Please wait.

Presentation is loading. Please wait.

Buzzback Inheritance Class Hierarchies Deferred Classes.

Similar presentations


Presentation on theme: "Buzzback Inheritance Class Hierarchies Deferred Classes."— Presentation transcript:

1 Buzzback Inheritance Class Hierarchies Deferred Classes

2 Buzzback

3 Buzzback Likes Lab is great! My TA is great! PowerPoint is great! LectureBonuses ® are great!

4 Buzzback Complaints Lab is terrible Why am I taking this? I’m never going to use this! Course is too hard! Why don’t we use a real language instead of this icky pseudocode TOO MUCH TIME/NOT ENOUGH CREDIT

5 Buzzback Complaints TA Consistency TA’s abusive Quizzes too hard Posting an already asked question should lose one point “Are you talking through your beard ‘cause it sounds kinda muffled?”

6 Buzzback Complaints Can’t hear you –Requested microphone –Pass notes to one another

7 Inheritance

8 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

9 Elevator Instances Lobby Doors Passenger Elevator #1 Passenger Elevator #2 Passenger Elevator #3 Service Elevator

10 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”

11 Relationships between Classes: Being - “Is-A” Elevator Open Doors Close Doors Position Doors Door Open Close IsOpen Thing Move Identity Color State “Is-A”

12 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

13 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

14 Inheritance Example Elevator Open Doors Close Doors Position Doors Door Open Close IsOpen Thing Move Identity Color State

15 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.

16 Inheriting from a SuperClass class inherits public protected endclass //

17 Two Types of Inheritance Extension –Adds attributes and methods Redefinition –Changes/modifies existing methods, specializing as needed

18 Inheritance Examples Given a bank account class… Extension –Add the capability of calculating interest Redefinition –Redefine how withdraws occur

19 Consider a primitive bank account which allows only three kinds of transactions: – Deposits – Withdrawals – Ability to check current balance Inheritance Example: Bank Accounts

20 The Base Class Bank_Account Bank_Account balance Deposit Withdraw Initialize Get_Balance

21 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

22 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

23 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.

24 Illustration of Inheritance Bank_Account balance Deposit Withdraw Initialize Get_Balance Savings_Account RATE MIN_BALANCE Calc_Interest // protected section Function Calc_Interest... endfunction

25 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

26 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

27 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

28 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,

29 Illustration of Redefinition Savings_Account RATE MIN_BALANCE Calc_Interest Cool_Savings overdraft_ok OVERDRAFT_CHARGE Allow_Overdraft // protected section procedure Withdraw... procedure Initialize...

30 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

31 // 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)

32 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.

33 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

34 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.

35 Questions?

36 Class Hierarchies

37 A Vehicle Class Hierarchy Vehicle VIN, Year Make Model Car Num_doors Body_type Truck Gross_weight Sedan HasAirbags Convertible Has_rollbar

38 Correctly Defining Class Hierarchies Move up common attributes and methods as far as possible Specialize particular classes lower –Redefine methods –Extend, adding methods & attributes

39 The Banking Class Hierarchy Cool Savings Bank Account Savings Account Checking Account NOW Account Money Market Account CD Account

40 Coad-Nicola Diagrams LB Class Name Attributes Methods Queue head tail Enqueue Dequeue isEmpty isFull Initialize

41 The Banking Class Hierarchy Cool Savings overdraft_ok OVERDRAFT_CHARGE Withdraw Initialize Bank Account balance Deposit Withdraw GetBalance Initialize Savings Account RATE MIN_BALANCE Calc_Interest Redefined

42 Resolving Ambiguities Each service request is satisfied according to the definition found at the lowest, most specific level beginning with the class of the object on which the method is invoked. Move up the hierarchy as far as needed. Stop when a matching implementation is found.

43 Cool Savings overdraft_ok OVERDRAFT_CHARGE Withdraw Initialize Bank Account balance Deposit Withdraw GetBalance Initialize Savings Account RATE MIN_BALANCE Calc_Interest MyCoolSavings iot CoolSavings... // from CoolSavings class MyCoolSavings.Withdraw(amount) // from SavingsAccount class interest <- MyCoolSavings.Calc_Interest // from BankAccount class MyCoolSavings.Deposit(1000)

44 Cool Savings overdraft_ok OVERDRAFT_CHARGE Withdraw Initialize Bank Account balance Deposit Withdraw GetBalance Initialize Savings Account RATE MIN_BALANCE Calc_Interest MyCoolSavings iot CoolSavings... // from CoolSavings class MyCoolSavings.Withdraw(amount) // from SavingsAccount class interest <- MyCoolSavings.Calc_Interest // from BankAccount class MyCoolSavings.Deposit(1000) ?

45 Cool Savings overdraft_ok OVERDRAFT_CHARGE Withdraw Initialize Bank Account balance Deposit Withdraw GetBalance Initialize Savings Account RATE MIN_BALANCE Calc_Interest MyCoolSavings iot CoolSavings... // from CoolSavings class MyCoolSavings.Withdraw(amount) // from SavingsAccount class interest <- MyCoolSavings.Calc_Interest // from BankAccount class MyCoolSavings.Deposit(1000)

46 Cool Savings overdraft_ok OVERDRAFT_CHARGE Withdraw Initialize Bank Account balance Deposit Withdraw GetBalance Initialize Savings Account RATE MIN_BALANCE Calc_Interest MyCoolSavings iot CoolSavings... // from CoolSavings class MyCoolSavings.Withdraw(amount) // from SavingsAccount class interest <- MyCoolSavings.Calc_Interest // from BankAccount class MyCoolSavings.Deposit(1000) ?

47 Cool Savings overdraft_ok OVERDRAFT_CHARGE Withdraw Initialize Bank Account balance Deposit Withdraw GetBalance Initialize Savings Account RATE MIN_BALANCE Calc_Interest MyCoolSavings iot CoolSavings... // from CoolSavings class MyCoolSavings.Withdraw(amount) // from SavingsAccount class interest <- MyCoolSavings.Calc_Interest // from BankAccount class MyCoolSavings.Deposit(1000) ?

48 Cool Savings overdraft_ok OVERDRAFT_CHARGE Withdraw Initialize Bank Account balance Deposit Withdraw GetBalance Initialize Savings Account RATE MIN_BALANCE Calc_Interest MyCoolSavings iot CoolSavings... // from CoolSavings class MyCoolSavings.Withdraw(amount) // from SavingsAccount class interest <- MyCoolSavings.Calc_Interest // from BankAccount class MyCoolSavings.Deposit(1000)

49 Summary Declare common methods/attributes as high in the class hierarchy as possible All subclasses will inherit these capabilities Specialize (extend and redefine) in subclasses When a method is invoked, the request is serviced by the lowest, most specific class and moves up as needed to find a match

50 Questions?

51 Deferred Classes

52 The Scenario You’re working at a theme park modeling an African Safari. Your boss wants each worker to implement a class for one of the animals.

53 Ensuring Correct Behavior Certain methods must be implemented for the animatronics to work: –Move –Eat –Sleep How can we be sure that every class has these methods?

54 The Animal Class Hierarchy Animal Move Eat Sleep LionGiraffeAntelopeBird

55 Problem Each animal will have a Move, Eat and Sleep method But they will all be different depending on the animal LB

56 Deferred Classes In designing a class hierarchy and an object-oriented solution to a problem, there are times when certain methods should appear higher in the class hierarchy than their implementation The class has the ability in an abstract sense But the implementation is unknown until a subclass.

57 Deferred Classes Defined A deferred class is any class which has a deferred method Deferred methods are any method which cannot be fully implemented. Deferred methods act as “place holders” in a design sense.

58 Solution class Animal public... protected... Procedure Move endprocedure // Move Procedure Eat endprocedure // Eat Procedure Sleep endprocedure // Sleep LB

59 Solution class Animal is deferred public... protected... Procedure Move endprocedure // Move Procedure Eat endprocedure // Eat Procedure Sleep endprocedure // Sleep LB

60 Assume that we are modeling geometric shapes, according to the hierarchy: Each particular shape will have some method of calculating its Area, Perimeter, etc … So, the shared superclass Shape should too... But, Shape doesn’t (can’t) know how! Shape CircleRectangleTriangle SquareEquilateral Another Example: Shapes

61 Declaring Deferred Classes class Shape is deferred public function Get_Area returnsa num // contract goes here function Get_Perimeter returnsa num // contract goes here protected function Get_Area returnsa num // can’t implement endfunction // Get_Area function Get_Perimeter returnsa num // can’t implement endfunction // Get_Perimeter endclass // Shape

62 Inheriting from Deferred Classes class Circle inherits Shape public // add accessor methods for radius // do NOT redeclare Get_Area or Get_Per. protected PI is 3.1415 radius isoftype num function Get_Area returnsa num Get_Area returns radius * radius * PI endfunction // Get_Area function Get_Perimeter returnsa num Get_Perimeter returns 2 * radius * PI endfunction // Get_Perimeter... endclass // Circle

63 The Shape Example With Shape including deferred methods: –All its subclasses MUST implement methods Get_Area and Get_Perimeter (either directly or by inheriting from another subclass that has them). –Shape itself is a deferred (or abstract) class: we can use it polymorphically to hold objects of one or more subclasses of Shape –But cannot manipulate any Shapes, per se: there is no reason to have actual instances of Shape, only instances of its subclasses. –Any class having one or more deferred methods is an abstract class, useful for abstracting out the attributes of its subclasses and for polymorphic purposes.

64 Summary A deferred method establishes a behavior (interface) but cannot implement it Subclasses must implement and conform to these behaviors Any class which contains a deferred method is a deferred class and should only be used polymorphically (next segment).

65 Questions?

66 Things to think about... Suppose you have a class Shape and subclasses Circle, Triangle, Rectangle, etc. How could you store a collection of Shapes? Suppose you wanted to go through the entire collection. How would you be able to tell each different shape to calculate its Area?

67


Download ppt "Buzzback Inheritance Class Hierarchies Deferred Classes."

Similar presentations


Ads by Google