I have a method inside my derived class that I don’t have in my base class, is there any way to use the derived class method on an object with the base class type? I know that I can move the method to my base class but I don’t think I am supposed to do that..
Here is the code:
I want to use CalculateInterest() on my accounts in my loop, but the accounts are all of type Account, not SavingsAccount.
Method in SavingsAccount class:
public decimal CalculateInterest()
{
return AcctBalance * interestRate;
}
Loop in Main:
List<Account> accounts = new List<Account>();
Account sAcct1 = new SavingsAccount(200, 0.10M);
Account sAcct2 = new SavingsAccount(300, 0.12M);
Account cAcct1 = new CheckingAccount(500, 2.00M);
Account cAcct2 = new CheckingAccount(400, 1.50M);
accounts.Add(sAcct1);
accounts.Add(sAcct2);
accounts.Add(cAcct1);
accounts.Add(cAcct2);
foreach (Account account in accounts)
{
account.Debit(decimal.Parse(Console.ReadLine()));
account.Credit(decimal.Parse(Console.ReadLine()));
if (account.GetType().ToString().Contains("SavingsAccount"))
{
//calculate interest if object is a savings account
}
}
In this case, probably best to have a default implementation of
calculateInterest()in the base class that does nothing.Subclasses would override to provide account-type-specific interest calculations.