In many cases, the overriding methods will have similar
functionality to the methods they override. It is counterproductive to the
concept of inheritance to just rewrite the same methods again with
slightly altered code. Inheritance exists to make code reuse as easy as
possible. As such, it provides a way to avoid rewriting the superclass
method. Simply insert the word super
with all the parameters that would be used to call the superclass method
bearing the same name wherever you would like the superclass’s method,
just like the initialize
method.
Applying this to our new SavingsAccount
class, we get the code in Example 10-3.
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
super
(
amount
)
17
else
18
puts
"Balance cannot drop below: "
+
@minimum
.
to_s
19
end
20
end
21
end
In our example, obviously the benefits seem minimal. However, for
complex programs, the advantages of using predefined classes are
tremendous. Not only are we saving ourselves the time of rewriting the
class, but we are also making code maintenance easier. If the withdraw
method needs to be updated, we can
update it in the Account
class. Any
subclasses that use it as their superclass will be updated accordingly,
wherever they have called super
.
3.145.179.85