Hide the Withdraw() method in the base class with a method in the subclass of the same name using polymorphism - CSharp Custom Type

CSharp examples for Custom Type:virtual

Description

Hide the Withdraw() method in the base class with a method in the subclass of the same name using polymorphism

Demo Code

using System;/* w ww.jav  a2 s  . com*/
public class Account
{
   protected decimal _balance;
   public Account(decimal initialBalance)
   {
      _balance = initialBalance;
   }
   public decimal Balance
   {
      get { return _balance; }
   }
   public decimal Withdraw(decimal 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);
   }
   new public decimal Withdraw(decimal withdrawal)
   {
      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;
      ba = new Account(200M);
      MakeAWithdrawal(ba, 100M);
      sa = new InvestmentAccount(200M, 12);
      MakeAWithdrawal(sa, 100M);
      Console.WriteLine("Account balance is {0:C}", ba.Balance);
      Console.WriteLine("InvestmentAccount balance is {0:C}", sa.Balance);
   }
}

Result


Related Tutorials