Changes

Jump to: navigation, search

Objective-C Inheritance

2,034 bytes added, 19:08, 26 October 2009
Extending the Functionality of a Subclass
</pre>
With these changes made we now have a class that inherits the features of the BankAccount class but nowhas an additional instance variable in the form of ''interestRate'' and two new methods named ''calculateInterest'' and ''setInterestRate''. The rest of the functionality we needed we essentially got for free by inheriting from the BankAccount class. == Overriding Inherited Methods == Whens 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 what you need. One option in this scenario would be to ignore the inherited method 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 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: <pre>@interface SavingsAccount: BankAccount{ float interestRate;}-(float) calculateInterest;-(void) setInterestRate: (float) y;-(void) displayAccountInfo;@end @implementation SavingsAccount-(float) calculateInterest{ return interestRate * accountBalance;} -(void) setInterestRate: (float) y{ interestRate = y;} -(void) displayAccountInfo{ NSLog (@"Account Number %i has a balance of %f and is earning %f interest", accountNumber, accountBalance, interestRate);}@end</pre>

Navigation menu