public abstract class Account
{
private string name; // Only accessible in base class
protected double balance;// Accessible in base class and derived Class
//constructor to initialize these fields
public Account(string nm, double bal)
{
this.name = nm;
this.balance = bal;
}
//The virtual keyword means these methods can be overridden in derived classes:
public virtual void Credit(double amount)
{
this.balance += amount;
}
public virtual void Debit(double amount)
{
this.balance -= amount;
}
public virtual void Display()
{
Console.WriteLine("Name={0}, balance={1}", this.name,this.balance);
}
//this method is not marked as virtual, it cannot be overridden in derived classes.
//This method provides the capability to change the name of the account holder.
public void ChangeName(string newName)
{
this.name = newName;
}
//The abstract keyword means this method must be overridden in derived classes:
public abstract double CalculateBankCharge();
}
public class SavingsAccount : Account
{
private double minBalance;// If the balance drops below minBalance, the bank will charge a fee on the account
//Modify the SavingsAccount constructor to initialize the fields in the base class and in this class:
public SavingsAccount(string nm, double bal, double min)
: base(nm, bal)// Call base-class constructor first
{
minBalance = min; // Then initialize fields in this class
}
//These methods override the virtual methods inherited from the base class:
public override void Debit(double amount)
{
if (amount <= balance) // Use balance, inherited from base class
base.Debit(amount); // Call Debit, inherited from base class
}
public override void Display()
{
base.Display();// Call Display, inherited from base class
Console.WriteLine("$5 charge if balance goes below ${0}", minBalance);
}
//You must override all abstract methods from the base class
public override double CalculateBankCharge()
{
if (balance < minBalance)
return 5.00;
else
return 0.00;
}
}
static void
{
//Account aca = new Account("sd", 1.1);//Cannot create an instance of the abstract class or interface
SavingsAccount sa = new SavingsAccount("Senthil", 100.00, 25);
sa.Display();
//call public methods in SavingsAccount or Account
sa.Credit(100);
sa.Debit(180);
sa.ChangeName("Kumar");
sa.Display();
Console.WriteLine("Bank charge: ${0}", sa.CalculateBankCharge());
}
Ref: http://support.microsoft.com/kb/307205
No comments:
Post a Comment