Changes

Jump to: navigation, search

Objective-C Inheritance

750 bytes added, 19:18, 26 October 2009
Overriding Inherited Methods
== Overriding Inherited Methods ==
Whens When using inheritance it is not unusual to find a method in the parent class that almost does what you need, but requires modification to provide the precise functionality you need. That said, it is also possible you'll inherit a method with a name that describes exactly what you want to do, but it actually does not do come close to doing what you need. One option in this scenario would be to ignore the inherited method and write a new method with an entirely new name. A better option is to ''override'' the inherited method and write a new version of it in the subclass.
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>

Navigation menu