34,333
edits
Changes
→Overriding Inherited Methods
== Overriding Inherited Methods ==
Before proceeding with an example, there are two rules that must be obeyed when overriding a method. Firstly, the overriding method in the subclass must take exactly the same number and type of arguments as the overridden class in the parent. Secondly, the new method must have the same return type and the parent method.
In our BankAccount class we have a method called ''displayAccountInfo'' that displays the bank account number and current balance held by an instance of the class. In our ''SavingsAccount'' subclass we might also want to output the current interest rate assigned to the account. To achieve this, we simply declare a new version of the ''displayAccountInfo'' method:
}
@end
</pre>
Now that we have completed work on our SavingsAccount class we can write some code to create an instance and start manipulating the object using our inherited, overridden and subclass specific methods:
<pre>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SavingsAccount *account1 = [[SavingsAccount alloc] init];
[account1 setAccount: 4543455 andBalance: 3010.10];
[account1 setInterestRate: 0.001];
float interestEarned = [account1 calculateInterest];
NSLog (@"Interest earned = %f", interestEarned);
[account1 displayAccountInfo];
[pool drain];
return 0;
}
</pre>