10.3 Basic Method Overriding
When extending a class, it is sometimes convenient to alter methods
that already exist in the class’s superclass. For example, both the
checking and saving accounts need a method for withdrawing money. However,
the methods are only the same on the outside. Unlike the regular checking
account, the savings account needs to check if the balance would fall
below the minimum allowed. To achieve this, the SavingsAccount
class will need to override the
withdraw
method by defining its own
withdraw functionality, as shown in Example 10-2. Overriding is accomplished by
using the same name in the local class. The local definition always
supersedes the parent definition.
1
require_relative
'../chapter_09/account_5.rb'
2
3
class
SavingsAccount
<
Account
4
def
initialize
(
balance
,
name
,
phone_number
,
interest
,
minimum
)
5
super
(
balance
,
name
,
phone_number
)
6
@interest
=
interest
7
@minimum
=
minimum
8
end
9
10
def
accumulate_interest
11
@balance
+=
@balance
*
@interest
12
end
13
14
def
withdraw
(
amount
)
15
if
(
@balance
-
amount
>=
@minimum
)
16
@balance
-=
amount
17
else
18
puts
"Balance cannot drop below: "
+
@minimum
.
to_s
19
end
20
end
21
end
Instead of calling on the withdraw
method that belongs to Account
, the SavingsAccount
class will use the new withdraw
method that overrode it. As a result,
any instances of SavingsAccount
will not be able to fall below their minimum account balances. This powerful property of OOP has ...
Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.