Hide a method in the base class polymorphically using the virtual and override keywords. - CSharp Custom Type

CSharp examples for Custom Type:virtual

Description

Hide a method in the base class polymorphically using the virtual and override keywords.

Demo Code

using System;//ww  w  .jav a2s  . c  o  m
public class Account
{
   protected decimal _balance;
   public Account(decimal initialBalance)
   {
      _balance = initialBalance;
   }
   public decimal Balance
   {
      get { return _balance; }
   }
   public virtual decimal Withdraw(decimal amount)
   {
      Console.WriteLine("In Account.Withdraw() for ${0}...", amount);
      decimal amountToWithdraw = amount;
      if (amountToWithdraw > Balance)
      {
         amountToWithdraw = Balance;
      }
      _balance -= amountToWithdraw;
      return amountToWithdraw;
   }
}
public class InvestmentAccount : Account
{
   public decimal _interestRate;
   public InvestmentAccount(decimal initialBalance, decimal interestRate): base(initialBalance)
   {
      _interestRate = interestRate / 100;
   }
   public void AccumulateInterest()
   {
      _balance = Balance + (Balance * _interestRate);
   }
   override public decimal Withdraw(decimal withdrawal)
   {
      Console.WriteLine("In InvestmentAccount.Withdraw()...");
      Console.WriteLine("Invoking base-class Withdraw twice...");
      base.Withdraw(1.5M);
      return base.Withdraw(withdrawal);
   }
}
public class Program
{
   public static void MakeAWithdrawal(Account ba, decimal amount)
   {
      ba.Withdraw(amount);
   }
   public static void Main(string[] args)
   {
      Account ba;
      InvestmentAccount sa;
      Console.WriteLine("Withdrawal: MakeAWithdrawal(ba, ...)");
      ba = new Account(200M);
      MakeAWithdrawal(ba, 100M);
      Console.WriteLine("Account balance is {0:C}", ba.Balance);
      Console.WriteLine("Withdrawal: MakeAWithdrawal(sa, ...)");
      sa = new InvestmentAccount(200M, 12);
      MakeAWithdrawal(sa, 100M);
      Console.WriteLine("InvestmentAccount balance is {0:C}", sa.Balance);
   }
}

Result


Related Tutorials