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
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?”
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
Elevator Instances
Lobby
Doors Doors
Doors Doors
Doors
Passenger Elevator #1
Passenger Elevator #2
Passenger Elevator #3
Service Elevator
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”
Relationships between Classes:Being - “Is-A”
ElevatorOpen Doors
Close Doors
• Position
• Doors
Door
Open
Close
• IsOpen
Thing
Move
• Identity• Color• State
“Is-A”
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
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
Elevator Door
Inheritance Example
ElevatorOpen Doors
Close Doors
• Position
• Doors
Door
Open
Close
• IsOpen
Thing
Move
• Identity• Color• State
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.
Inheriting from a SuperClass
class <SUBCLASS_NAME>
inherits <SUPERCLASS_NAME>
public
<CHANGES>
protected
<CHANGES>
endclass // <SUBCLASS_NAME>
Two Types of Inheritance
• Extension– Adds attributes and methods
• Redefinition– Changes/modifies existing methods,
specializing as needed
Inheritance Examples
Given a bank account class…
• Extension– Add the capability of calculating interest
• Redefinition– Redefine how withdraws occur
• Consider a primitive bank account which allows only three kinds of transactions:– Deposits– Withdrawals– Ability to check current balance
Inheritance Example: Bank Accounts
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
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
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.
Illustration of InheritanceBank_Account
• balance
Deposit
Withdraw
Initialize
Get_Balance
Savings_Account • RATE• MIN_BALANCECalc_Interest
// protected section
Function Calc_Interest
. . .
endfunction
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
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
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 methodendalgorithm // BankExample
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,
Illustration of RedefinitionSavings_Account
• RATE• MIN_BALANCE
Calc_Interest
Cool_Savings
• overdraft_ok• OVERDRAFT_CHARGEAllow_Overdraft
// protected section
procedure Withdraw
. . .
procedure Initialize
. . .
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
// 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)
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.
Using Subclasses in Algorithms
my_cool_savings isoftype Cool_Savingsmy_cool_savings.Initialize // bothmy_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 Nummy_interest <- my_cool_savings.Calc_Interest // super method. . .my_cool_savings.Withdraw(amount)// subclass method
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.
A Vehicle Class Hierarchy
VehicleVIN, YearMakeModel
CarNum_doorsBody_type
TruckGross_weight
SedanHasAirbags
ConvertibleHas_rollbar
Correctly Defining Class Hierarchies
• Move up common attributes and methods as far as possible
• Specialize particular classes lower– Redefine methods– Extend, adding methods & attributes
The Banking Class Hierarchy
Cool Savings
Bank Account
Savings Account
Checking Account
NOW Account
Money Market Account
CD Account
Coad-Nicola Diagrams
LB
Class Name
Attributes
Methods
Queue
headtail
EnqueueDequeueisEmpty
isFullInitialize
The BankingClass Hierarchy
Cool Savingsoverdraft_ok
OVERDRAFT_CHARGEWithdrawInitialize
Bank AccountbalanceDeposit
WithdrawGetBalance
Initialize
Savings AccountRATE
MIN_BALANCECalc_Interest
Redefined
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.
Cool Savingsoverdraft_ok
OVERDRAFT_CHARGEWithdrawInitialize
Bank AccountbalanceDeposit
WithdrawGetBalance
Initialize
Savings AccountRATE
MIN_BALANCECalc_Interest
MyCoolSavings iot CoolSavings
. . .
// from CoolSavings class
MyCoolSavings.Withdraw(amount)
// from SavingsAccount class
interest <- MyCoolSavings.Calc_Interest
// from BankAccount class
MyCoolSavings.Deposit(1000)
Cool Savingsoverdraft_ok
OVERDRAFT_CHARGEWithdrawInitialize
Bank AccountbalanceDeposit
WithdrawGetBalance
Initialize
Savings AccountRATE
MIN_BALANCECalc_Interest
MyCoolSavings iot CoolSavings
. . .
// from CoolSavings class
MyCoolSavings.Withdraw(amount)
// from SavingsAccount class
interest <- MyCoolSavings.Calc_Interest
// from BankAccount class
MyCoolSavings.Deposit(1000)
?
Cool Savingsoverdraft_ok
OVERDRAFT_CHARGEWithdrawInitialize
Bank AccountbalanceDeposit
WithdrawGetBalance
Initialize
Savings AccountRATE
MIN_BALANCECalc_Interest
MyCoolSavings iot CoolSavings
. . .
// from CoolSavings class
MyCoolSavings.Withdraw(amount)
// from SavingsAccount class
interest <- MyCoolSavings.Calc_Interest
// from BankAccount class
MyCoolSavings.Deposit(1000)
Cool Savingsoverdraft_ok
OVERDRAFT_CHARGEWithdrawInitialize
Bank AccountbalanceDeposit
WithdrawGetBalance
Initialize
Savings AccountRATE
MIN_BALANCECalc_Interest
MyCoolSavings iot CoolSavings
. . .
// from CoolSavings class
MyCoolSavings.Withdraw(amount)
// from SavingsAccount class
interest <- MyCoolSavings.Calc_Interest
// from BankAccount class
MyCoolSavings.Deposit(1000)
?
Cool Savingsoverdraft_ok
OVERDRAFT_CHARGEWithdrawInitialize
Bank AccountbalanceDeposit
WithdrawGetBalance
Initialize
Savings AccountRATE
MIN_BALANCECalc_Interest
MyCoolSavings iot CoolSavings
. . .
// from CoolSavings class
MyCoolSavings.Withdraw(amount)
// from SavingsAccount class
interest <- MyCoolSavings.Calc_Interest
// from BankAccount class
MyCoolSavings.Deposit(1000)
?
Cool Savingsoverdraft_ok
OVERDRAFT_CHARGEWithdrawInitialize
Bank AccountbalanceDeposit
WithdrawGetBalance
Initialize
Savings AccountRATE
MIN_BALANCECalc_Interest
MyCoolSavings iot CoolSavings
. . .
// from CoolSavings class
MyCoolSavings.Withdraw(amount)
// from SavingsAccount class
interest <- MyCoolSavings.Calc_Interest
// from BankAccount class
MyCoolSavings.Deposit(1000)
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 upas needed to find a match
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.
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?
Problem
• Each animal will have a Move, Eat and Sleep method
• But they will all be different depending on the animal
LB
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.
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.
Solution
class Animal
public
...
protected
...
Procedure Move
endprocedure // Move
Procedure Eat
endprocedure // Eat
Procedure Sleep
endprocedure // Sleep
LB
Solution
class Animal is deferred
public
...
protected
...
Procedure Move
endprocedure // Move
Procedure Eat
endprocedure // Eat
Procedure Sleep
endprocedure // Sleep
LB
• 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
Circle Rectangle Triangle
Square Equilateral
Another Example: Shapes
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
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
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.
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).
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?