0% found this document useful (0 votes)
32 views12 pages

Exercise 1:: 1-Create 2 Classes: 2

The document describes a series of exercises to practice inheritance and polymorphism in C# by creating bank account classes. The exercises involve: 1. Creating Account and CheckingAccount classes with properties and methods like GetBalance() and Withdraw(). 2. Creating a form to test withdrawing from a CheckingAccount object. 3. Adding a GetBalance method that retrieves balances based on account number. 4. Creating a SavingsAccount class that inherits from Account. 5. Testing retrieving balances polymorphically based on the account type. 6. Making the GetBalance method protected to restrict its use to derived classes only. 7. Adding a Withdraw method to SavingsAccount that calls the protected Get

Uploaded by

charbeldaher34
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views12 pages

Exercise 1:: 1-Create 2 Classes: 2

The document describes a series of exercises to practice inheritance and polymorphism in C# by creating bank account classes. The exercises involve: 1. Creating Account and CheckingAccount classes with properties and methods like GetBalance() and Withdraw(). 2. Creating a form to test withdrawing from a CheckingAccount object. 3. Adding a GetBalance method that retrieves balances based on account number. 4. Creating a SavingsAccount class that inherits from Account. 5. Testing retrieving balances polymorphically based on the account type. 6. Making the GetBalance method protected to restrict its use to derived classes only. 7. Adding a Withdraw method to SavingsAccount that calls the protected Get

Uploaded by

charbeldaher34
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Exercise 1:

1- Create 2 classes: Account and CheckingAccount


2- Update your classes as follows:
class Account
{
long accountNumber;
public long AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
public double GetBalance()
{
//code to retrieve account balance from database
return (double)10000;
}
}
class CheckingAccount : Account
{
double minBalance;
public double MinBalance
{
get { return minBalance; }
set { minBalance = value; }
}
public void Withdraw(double amount)
{
//code to withdraw from account
}
}
3- Create a form and name it to “test”. Add a “Go” button to your form.
4- Double click on the “Go” button and Add the following code:
CheckingAccount oCheckingAccount = new CheckingAccount();
double balance;
oCheckingAccount.AccountNumber = 1000;
balance = oCheckingAccount.GetBalance();
oCheckingAccount.Withdraw(500);

5- Add the following GetBalance method to the Account class:

public double GetBalance(int accountNumber)


{
accountNumber = accountNumber;
//Data normally retrieved from database.
if ( accountNumber == 1)
{
return 1000;
}
else if ( accountNumber == 2)
{
return 2000;
}
else
{
throw new Exception("Account number is incorrect");
}
}

6- After the Account class, add the following code to create the SavingsAccount derived
classe:
class SavingsAccount : Account
{
}
7- Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
Exercise 2:
Testing the Classes
To test the classes, follow these steps:
1. Open the Teller form in the code editor and locate the btnGetBalance click event code.
2. Inside the event procedure, prior to the Try block, declare and instantiate a variable of type
CheckingAccount called oCheckingAccount, a variable of type SavingsAccount called
oSavingsAccount, and a variable of type Account called oAccount:

CheckingAccount oCheckingAccount = new CheckingAccount();


SavingsAccount oSavingsAccount = new SavingsAccount();
Account oAccount = new Account();

3. Depending on which radio button is selected, call the GetBalance method of the
appropriate object and pass the account number value from the Account Number text box.
Show the return value in the Balance text box. Place the following code in the Try block prior
to the Catch statement:

if (rdbChecking.Checked)
{
txtBalance.Text =
oCheckingAccount.GetBalance(int.Parse(txtAccountNumber.Text)).ToString();
}
else if (rdbSavings.Checked)
{
txtBalance.Text =
oSavingsAccount.GetBalance(int.Parse(txtAccountNumber.Text)).ToString();
}
else if (rdbGeneral.Checked)
{
txtBalance.Text =
oAccount.GetBalance(int.Parse(txtAccountNumber.Text)).ToString();
}

4. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
5. Select Debug ➤ Start to run the project. Enter an account number of 1 and click the Get
Balance button for the Checking Account type. You should get a balance of 1,000. Test the
other account types. You should get the same result, since all classes are using the same
GetBalance function defined in the base class.
6. After testing, close the form, which will stop the debugger.
Exercise 3:

Restricting Use of a Base Class Method to Its Derived Classes


At this point, the GetBalance method of the base class is public, which means that it can be
accessed by derived classes and their clients. Let’s alter this so that the GetBalance method
can be accessed only by the derived classes alone, and not by their clients. To protect the
GetBalance method in this way, follow these steps:
1. Locate the GetBalance method of the Account class.
2. Change the access modifier of the GetBalance method from public to protected.
3. Switch to the frmTeller code editor and locate the btnGetBalance click event code.
4. Hover the cursor over the call to the GetBalance method of the oCheckingAccount object.
You will see a warning stating that it is a protected function and is not accessible in this
context.
5. Comment out the code between the Try and the Catch statements.
6. Switch to the Account.cs code editor.
7. Add the following code to create the following private instance variable to the
SavingsAccount class definition file:
double dblBalance;
8. Add the following Withdraw method to the SavingsAccount class. This function calls the
protected method of the Account base class:

public double Withdraw(int accountNumber, double amount)


{
dblBalance = GetBalance(accountNumber);
if ( dblBalance >= amount)
{
dblBalance -= amount;
return dblBalance;
}
else
{
throw new Exception("Not enough funds.");
}
}
9. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
Exercise 4:

Testing the Protected Base Class Method


To test the Withdraw method, follow these steps:
1. Open the frmTeller form in the code editor and locate the btnWithdraw click event code.
2. Inside the event procedure, prior to the Try block, declare and instantiate a variable of type
SavingsAccount called oSavingsAccount.
SavingsAccount oSavingsAccount = new SavingsAccount();
3. Call the Withdraw method of the oSavingsAccount. Pass the account number value from
the Account Number text box and the withdrawal amount from the Amount text box. Show
the return value in the Balance text box. Place the following code in the Try block prior to the
Catch statement:
txtBalance.Text = oSavingsAccount.Withdraw
(int.Parse(txtAccountNumber.Text),double.Parse(txtAmount.Text)).ToString();
4. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them and then rebuild.
5. Select Debug ➤ Start to run the project.
6. Test the Withdraw method of the SavingsAccount class by entering an account number of
1 and a withdrawal amount of 200. Click the Withdraw button. You should get a resulting
balance of 800.
7. Enter an account number of 1 and a withdrawal amount of 2000. Click the Withdraw
button. You should get an insufficient funds message.
8. After testing the Withdraw method, close the form, which will stop the debugger.
Exercise 5:

Restricting Use of All Members of a Base Class to its Derived Classes


Because the Account base class is public, it can be instantiated by clients of the derived
classes. You can alter this by making the Account base class an abstract class. An abstract
class can be accessed only by its derived classes and can’t be instantiated and accessed by
their clients. To create and test the accessibility of the abstract class, follow these steps:
1. Locate the Account class definition in the Account.cs code.
2. Add the abstract keyword to the class definition code, like so:
abstract class Account
3. Select Build ➤ Build Solution. You should receive a build error in the Error List window.
Find the line of code causing the error.
Account oAccount = new Account();
4. Comment out the line of code, and select Build ➤ Build Solution again. It should now
build without any errors.
5. Save and close the project.
Exercise 6:

Testing the Overwritten Methods


To test the modified Withdraw methods you have created, follow these steps:
1. Open the frmTeller form in the code editor and locate the btnWithdraw click event code.
2. Depending on which radio button is selected, call the Withdraw method of the appropriate
object and pass the value of the txtAmount text box. Add the following code in the try block
to show the return value in the txtBalance text box:

if (rdbChecking.Checked)
{
oCheckingAccount.AccountNumber = int.Parse(txtAccountNumber.Text);
txtBalance.Text =
oCheckingAccount.Withdraw(double.Parse(txtAmount.Text)).ToString();
}
else if (rdbSavings.Checked)
{
oSavingsAccount.AccountNumber = int.Parse(txtAccountNumber.Text);
txtBalance.Text =
oSavingsAccount.Withdraw(double.Parse(txtAmount.Text)).ToString();
}

3. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
4. Select Debug ➤ Start to run the project.
5. Enter an account number of 1, choose the Checking option button, and click the Get
Balance button.You should get a balance of 1000.
6. Enter a withdrawal amount of 200 and click the Withdraw button. You should get a
resulting balance of 800.
7. Enter a withdrawal amount of 700 and click the Withdraw button. You should get an
insufficient funds message because the resulting balance would be less than the minimum
balance of 200.
8. Enter an account number of 1, choose the Savings option button, and click the Get Balance
button. You should get a balance of 1000.
9. Enter a withdrawal amount of 600 and click the Withdraw button. You should get a
resulting balance of 400.
10. Enter a withdrawal amount of 400 and click the Withdraw button. You should get a
resulting balance of 0 because there is no minimum balance for the savings account that uses
the Account base class’s Withdraw method.
11. After testing, close the form, which will stop the debugger.
Exercise 7:

Using the Base Qualifier to Call a Base Class Method


At this point, the Withdraw method of the CheckingAccount class overrides the Account
class’s Withdraw method. None of the code in the base class’s method is executed. You will
now alter the code so that when the CheckingAccount class’s code is executed, it also
executes the base class’s Withdraw method . Follow these steps:
1. Locate the Withdraw method of the Account class.
2. Change the implementation code so that it decrements the balance by the amount passed to
it.

public virtual double Withdraw(double amount)


{
balance -= amount;
return Balance;
}

3. Change the Withdraw method of the CheckingAccount class so that after it checks for
sufficient funds, it calls the Withdraw method of the Account base class.

public override double Withdraw(double amount)


{
if (Balance >= amount + GetMinimumBalance())
{
return base.Withdraw(amount);
}
else
{
throw new ApplicationException("Not enough funds.");
}
}

4. Add a Withdraw method to the SavingsAccount class that is similar to the Withdraw
method of the CheckingAccount class but does not check for a minimum balance.

public override double Withdraw(double amount)


{
if (Balance >= amount)
{
return base.Withdraw(amount);
}
else
{
throw new ApplicationException("Not enough funds.");
}
}

5. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
Exercise 8:

Testing the Use of the Base Modifier


To test the Withdraw method, follow these steps:
1. Select Debug ➤ Start.
2. Enter an account number of 1, choose the Checking option button, and click the Get
Balance button. You should get a balance of 1000.
3. Enter a withdrawal amount of 600 and click the Withdraw button. You should get a
resulting balance of 400.
4. Enter a withdrawal amount of 300 and click the Withdraw button. You should get an
insufficient funds message because the resulting balance would be less than the 200
minimum.
5. Enter an account number of 1, choose the Savings option button, and click the Get Balance
button. You should get a balance of 1000.
6. Enter a withdrawal amount of 600 and click the Withdraw button. You should get a
resulting balance of 400.
7. Enter a withdrawal amount of 300 and click the Withdraw button. You should get a
resulting balance of 100, because there is no minimum balance for the savings account that
uses the Account base class’s Withdraw method.
8. After testing, close the form, which will stop the debugger.
Exercise 9:
Testing the Polymorphic Inheritance Method
To test the polymorphic method, follow these steps:
1. Open the Program.cs file in the code editor and locate the Main method.
2. Instantiate an instance of a list of Account types.
List<Account> AccountList = new List<Account>();
3. Instantiate an instance of the CheckingAccount and SavingsAccount.

CheckingAccount oCheckingAccount = new CheckingAccount();


oCheckingAccount.AccountNumber = 100;
SavingsAccount oSavingsAccount = new SavingsAccount();
oSavingsAccount.AccountNumber = 200;

4. Add the oCheckingAccount and oSavingsAccount to the list using the Add method of the
list.
AccountList.Add(oCheckingAccount);
AccountList.Add(oSavingsAccount);
5. Loop through the list and call the GetAccountInfo method of each Account type in
the list and show the results in a console window.

foreach (Account a in AccountList)


{
Console.WriteLine(a.GetAccountInfo());
}
Console.ReadLine();

6. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
7. Select Debug ➤ Start to run the project. You should see a console window with
the return string for the GetAccountInfo method of each object in the list.
8. After testing the polymorphism, hit the enter key to close the console window,
which will stop the debugger.
Exercise 10:
Implementing Polymorphism Using an Interface
To implement polymorphism using an interface, follow these steps:
1. View the code for the Account.cs file in the code editor.
2. Comment out the code for the Account, CheckingAccount, and SavingsAccount
classes.
3. Define an interface IAccount that contains the GetAccountInfo method.
public interface IAccount
{
string GetAccountInfo();
}
4. Add the following code to create two classes: CheckingAccount and SavingsAccount.
These classes will implement the IAccount interface.

public class CheckingAccount : IAccount


{
private int accountNumber;
public int AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
public string GetAccountInfo()
{
return "Printing checking account info for account number "
+ AccountNumber.ToString();
}
}
public class SavingsAccount : IAccount
{
private int accountNumber;
public int AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
public string GetAccountInfo()
{
return "Printing savings account info for account number " +
AccountNumber.ToString();
}
}

5. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
Exercise 11:
Testing the Polymorphic Interface Method
To test the polymorphic method, follow these steps:
1. Open the Program.cs file in the code editor and locate the Main method.
2. Change the code to instantiate an instance of a list of IAccount types.
List<IAccount> AccountList = new List<IAccount>();
3. Change the for each loop to loop through the list and call the GetAccountInfo()
method of each IAccount type in the list.

foreach (IAccount a in AccountList)


{
Console.WriteLine(a.GetAccountInfo());
}
Console.ReadLine();

4. Select Build ➤ Build Solution. Make sure there are no build errors in the Error List
window. If there are, fix them, and then rebuild.
5. Select Debug ➤ Start to run the project. You should see a console window with
the return string for the GetAccountInfo method of each object in the list.
6. After testing the polymorphism, hit the enter key to close the console window,
which will stop the debugger.

You might also like