9.4 super Keyword
When a subclass object is created, a superclass object is created in the process. This is evident in the initial call to super
that is made in the constructor:
In addition to creating the superclass object, the super
keyword can be used to reference the super object in other methods within the subclass.
The keyword super
is similar to the keyword this
. this
refers to the current object, while super
refers to the superclass object. Just as it’s possible to reference methods and pass parameters using the this
keyword, methods can be referenced and passed parameters using the super
keyword.
super
refers to the superclass object and can call methods using:
Here is a sample superclass Animal
:
The Dog
class extends the Animal
class, inheriting its methods and instance variables:
In this example, the Dog
subclass constructor uses the super
keyword to call the Animal
constructor. The Dog
class bark()
method also calls the superclass speak()
method by passing it a parameter that will then get used in the speak()
method.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
Given the following code, what is the correct way for the subclass to call the
speak
method in thePerson
class?
For this exercise, you will be completing the Account
class, which simulates a regular bank account, then using overrides and calls to the superclass to create a StudentAccount
.
Student accounts differ from regular accounts in that they get a 10% bonus for every deposit, but a $1.50 fee for every withdrawal. For instance, if you deposit $1.00 into a student account, your balance actually grows by $1.10 ($0.10 is 10% of $1.00). Likewise, if you withdraw $1.00, your balance actually shrinks by $2.50.
You will override the methods in the StudentAccount
by calling the superclass methods with the additional amount or fee incorporated since the balance is not directly stored in the StudentAccount
object.
You will also update the toString()
, as outlined in the comments.
When completed, create one student account and one regular account for testing. Deposit and withdraw money and print the results.