BankAccount: A Simple Example in .NET framework

Creator QR-Code in .NET framework BankAccount: A Simple Example

BankAccount: A Simple Example
Encoding QR Code In VS .NET
Using Barcode maker for .NET Control to generate, create QR Code image in Visual Studio .NET applications.
www.OnBarcode.com
Read Denso QR Bar Code In .NET
Using Barcode reader for .NET Control to read, scan read, scan image in Visual Studio .NET applications.
www.OnBarcode.com
The simple bank account provides the basis for this exercise in inheritance. You will implement a BankAccount class as a base class with the following members: Member Owner Description A string property that identifies the owner of the account. A read-only string property that identifies the account. A read-only decimal property. The value of this property depends on the deposits and withdrawals made to the account. This method takes one parameter: the amount to deposit. It returns the balance after the deposit. This method takes one
Generate Bar Code In .NET Framework
Using Barcode maker for .NET framework Control to generate, create bar code image in .NET applications.
www.OnBarcode.com
Bar Code Decoder In .NET
Using Barcode recognizer for .NET framework Control to read, scan read, scan image in .NET applications.
www.OnBarcode.com
Balance
Painting QR In C#.NET
Using Barcode creator for VS .NET Control to generate, create QR Code JIS X 0510 image in .NET framework applications.
www.OnBarcode.com
Printing Quick Response Code In .NET Framework
Using Barcode generation for ASP.NET Control to generate, create Denso QR Bar Code image in ASP.NET applications.
www.OnBarcode.com
Deposit
QR Code Creator In VB.NET
Using Barcode drawer for VS .NET Control to generate, create Denso QR Bar Code image in .NET framework applications.
www.OnBarcode.com
ANSI/AIM Code 39 Encoder In .NET Framework
Using Barcode maker for .NET Control to generate, create USS Code 39 image in .NET framework applications.
www.OnBarcode.com
Withdraw
EAN 13 Generator In .NET
Using Barcode creator for .NET framework Control to generate, create EAN 13 image in VS .NET applications.
www.OnBarcode.com
GTIN - 128 Creator In Visual Studio .NET
Using Barcode maker for Visual Studio .NET Control to generate, create GTIN - 128 image in Visual Studio .NET applications.
www.OnBarcode.com
Member
Make GS1 DataBar In Visual Studio .NET
Using Barcode encoder for .NET Control to generate, create GS1 RSS image in VS .NET applications.
www.OnBarcode.com
Print ISBN In .NET
Using Barcode encoder for Visual Studio .NET Control to generate, create ISBN - 10 image in Visual Studio .NET applications.
www.OnBarcode.com
Description parameter: the amount to withdraw. It returns the balance after the withdrawal.
UPC-A Supplement 2 Recognizer In Java
Using Barcode scanner for Java Control to read, scan read, scan image in Java applications.
www.OnBarcode.com
QR Code 2d Barcode Generation In Java
Using Barcode creation for BIRT Control to generate, create QR Code 2d barcode image in BIRT applications.
www.OnBarcode.com
Constructor
Bar Code Creator In .NET Framework
Using Barcode encoder for Reporting Service Control to generate, create bar code image in Reporting Service applications.
www.OnBarcode.com
Generating Bar Code In Objective-C
Using Barcode encoder for iPad Control to generate, create barcode image in iPad applications.
www.OnBarcode.com
The constructor takes one parameter: the account owner s name (a string), to use for the ID property.
Data Matrix 2d Barcode Printer In Objective-C
Using Barcode maker for iPad Control to generate, create Data Matrix ECC200 image in iPad applications.
www.OnBarcode.com
Printing PDF-417 2d Barcode In Java
Using Barcode creator for Java Control to generate, create PDF-417 2d barcode image in Java applications.
www.OnBarcode.com
Create the base class, BankAccount 1. Create a new project and name it TheBank. 2. On the Project menu, click Add Class. The Add New Item dialog box appears. 3. Name the file BankAccount.vb or BankAccount.cs, depending on the language you re using. Add the properties and constructor The account ID is based on the owner s name. In the limited world of this exercise, each person can have only one account, and all names are unique. So the ID is the same as the owner s name. 1. Add this code for the read-only ID property: 2. Visual Basic 3. Private m_owner As String 4. Public ReadOnly Property ID() As String 5. Get 6. Return m_owner 7. End Get 8. End Property 9. 10. // Visual C# 11. private string m_owner; 12. public string ID { 13. get { 14. return m_owner; 15. } 16. } The next property, Balance, will also be read-only. In the real world, you can t just tell the bank you have a certain amount of money. To change your balance, you have to make a deposit or a withdrawal. So it will be with this example: the Balance is read-only and can be changed only by means of the Deposit and Withdraw methods. The balance is stored in a decimal field. The decimal data type (System.Decimal) is used to store numbers with a particular precision. Thus 2.37 is stored as 2.37, not something extremely close to 2.37, as might happen in using a System.Double variable. The advantage of using the System.Decimal data type is that rounding doesn t occur, so the System.Decimal type is appropriate for representing currency.
Data Matrix 2d Barcode Encoder In None
Using Barcode maker for Software Control to generate, create Data Matrix image in Software applications.
www.OnBarcode.com
1D Barcode Printer In Java
Using Barcode drawer for Java Control to generate, create 1D Barcode image in Java applications.
www.OnBarcode.com
17. Add this code for the read-only Balance property: 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. } // Visual C# private decimal m_balance; public decimal Balance { get { return m_balance; Visual Basic Private m_balance As Decimal Public ReadOnly Property Balance() As Decimal Get Return m_balance End Get End Property
} 32. Add the following code to the BankAccount class to create a constructor. All accounts need to have an owner, so the only constructor provided has one string parameter for the owner s name. In Visual C#, replace the default constructor with the one below. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. } // Visual C# public BankAccount(string owner) { m_owner = owner; m_balance = 0M; Visual Basic Public Sub New(ByVal owner As String) m_owner = owner m_balance = 0D End Sub
Add the methods 1. Add the following code to the BankAccount class for the Deposit method. This method adds the indicated amount to the balance and returns the new balance. 2. Visual Basic 3. Public Function Deposit(ByVal amount As Decimal) As Decimal 4. m_balance += amount 5. Return m_balance 6. End Function 7. 8. // Visual C# 9. public decimal Deposit(decimal amount) { 10. m_balance += amount; 11. return m_balance; }
12. Add the following code to the BankAccount class for the Withdraw method. This method subtracts the indicated amount from the balance and returns the new balance. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. } Test the BankAccount interface The base class, BankAccount, is now complete. Before moving on to the first derived class, SavingsAccount, take a look at the public interface of the BankAccount class. 1. Open Form1 in the designer. 2. Double-click on the form to create the Form1_Load method in the code editor. 3. Add the following code to the method, and note the members displayed in IntelliSense, shown in the subsequent graphic. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. } // Visual C# private void Form1_Load(object sender, System.EventArgs e) { BankAccount account = new BankAccount("Robin"); account.Deposit(25M); MessageBox.Show(String.Format("{0:C}", account.Balance)); Visual Basic Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim account As BankAccount = New BankAccount("Robin") account.Deposit(25D) MessageBox.Show(String.Format("{0:C}", account.Balance)) End Sub // Visual C# public decimal Withdraw(decimal amount) { // since an assignment returns the assigned value, // only need one line return (m_balance -= amount); Visual Basic Public Function Withdraw(ByVal amount As Decimal) As Decimal m_balance -= amount Return m_balance End Function
String.Format The String.Format method gives you a way to create strings based on variable values without using long string concatenation statements. The String.Format method has several overloads. In each case, the first parameter is a format statement, which is a string that s interspersed with formatting specifications. For example, {0:C} specifies that a value should be converted to a string using a currency format. The rest of the parameters of the method are used to replace the formatting specifications. Thus the following statements are equivalent and produce You have $1.23 in the bank. String.Format("You have {0:C} in the bank.", balance) "You have " + balance.ToString("C") + " in the bank."
The class members contain the public properties and methods of the BankAccount class: Balance, ID, Deposit, and Withdraw. The members list also contains those members inherited from the Object class: GetType, Equals (C# only), GetHashCode (C# only), and ToString (C# only). In the next section, you ll create a derived class from BankAccount, and it will contain the public interface of Object and BankAccount. 12. Press F5 to run the application. The result is shown in the following screen. You have created the completely functional base class, BankAccount.
Creating the SavingsAccount Derived Class The first derived class you create will be the SavingsAccount class. In this example SavingsAccount is identical to BankAccount except in the following respects: A savings account offers interest. The SavingsAccount class will have an additional property, Interest. A savings account can accrue interest over time. The SavingsAccount class will have an additional method, AddInterest. One person can have both a savings account and a checking account, an expansion of your banking world. To distinguish between the two accounts, the ID property will indicate the type of account. Create the SavingsAccount class 1. On the Project menu, click Add Class. The Add New Item dialog box appears. 2. Name the file SavingsAccount.vb or SavingsAccount.cs, depending on the language you re using. 3. Modify the class declaration to indicate that BankAccount is the base class as shown here: 4. 5. 6. 7. Visual Basic Public Class SavingsAccount Inherits BankAccount End Class
8. 9. 10. 11. 12. 13. } // Visual C# public class SavingsAccount : TheBank.BankAccount { public SavingsAccount() { }
If you re using Visual Basic, the following message appears in the Task List: Cannot implicitly create a constructor for Class SavingsAccount because its base class BankAccount doesn t declare a public constructor that has no parameters. Either define a constructor on Class SavingsAccount or a parameterless constructor on base Class BankAccount . If you re using Visual C#, the following message appears in the Task List: No overload for method BankAccount takes 0 arguments As you create and modify base classes and derived classes, various messages appear in the Task List. These messages help you correctly implement the classes. Although inheritance lets you reuse much of the code in the base class, you will, of course, want to modify and add to the derived class. Getting the behavior you want in the derived classes requires a certain syntactical handshaking between the base class and derived classes. The messages that you receive as you work indicate that this handshaking isn t yet correctly implemented.
The C# Class Wizard The C# Class Wizard allows you to specify a base class when you create a new class. In the wizard, click the Base Class tab and click a class in the Base Class list. If the class you want to derive from isn t part of your project, first find the namespace that contains the class in the Namespace list.
Leaving the constructor work aside for a moment, modify the ID property so that you form the ID by adding -S to the end of the owner s name. This process has three steps: By default, the class inherits the behavior of the base class. To override this behavior, you redefine the property in the derived class and add the override modifier to the property declaration. In the base class, you modify the property declaration by adding the virtual keyword to it. Because the m_owner field in BankAccount is defined as a private field, it isn t accessible in the SavingsAccount code. And because the m_owner field is the basis for the ID, the third step is to redefine the scope of the m_owner field in the base class. The interaction between the virtual base class property and the overridden derived class property becomes apparent when the classes are used polymorphically.
Examine the development environment Take a moment to examine the changes in the development environment now that you have declared a base class for SavingsAccount. 1. Expand the Class View window. The base class and its members are now included as you see in the following screens. Notice the m_balance and m_owner fields have a small lock on the icon, indicating that they re private fields. A public field wouldn t have a lock.
17. If you re using Visual Basic, open the source file for the SavingsAccount class in the code editor. Click the Class Name list. Two new entries appear, (Overrides) and (Base Class Events). Click (Overrides) in the list and then examine the entries in the Method Name list. It s empty. As you add overridable properties and methods to the BankAccount class, they appear in the Method Name list.
Override the ID property 1. Open the BankAccount class in the code editor and modify the declaration of the m_owner field so that it s protected: 2. Visual Basic 3. Protected m_owner As String 4. 5. // Visual C# protected string m_owner; Protected fields are available to derived classes. They re treated as private in client code. Private fields aren t available to derived classes or client code. Not all class fields need to be protected. If you examine the class in the Class View, the icon on the m_owner field has a key on it, indicating that the field is protected. Modify the ID property by adding the Overridable or virtual keyword, as you see here: Visual Basic Public Overridable ReadOnly Property ID() As String Get Return m_owner End Get End Property // Visual C# virtual public string ID { get { return m_owner; } } 6. Open the SavingsAccount source file in the code editor. 7. If you re using Visual Basic, click (Overrides) in the Class List, and then click ID in the Method Name list. The following empty property definition is added to the class: 8. 9. 10. 11. 12. 13. End Get End Property Visual Basic Public Overrides ReadOnly Property ID() As String Get
If you re using Visual C#, expand the Bases And Interfaces node of the SavingsAccount class in the Class View. Expand the BankAccount node and right-click the ID property. On the shortcut menu, point to Add and then click Override. The following empty property definition is added to the class: // Visual C# public override string ID { get { return null; } } 14. Modify the property to return the ID. As you type in the code, notice the IntelliSense list as you type Me. or this. (including the period in either case). The list is shown in the screen that follows. 15. 16. 17. Visual Basic Public Overrides ReadOnly Property ID() As String Get
18. 19. 20. 21. 22. 23. 24. 25. 26. } }
Return Me.m_owner & "-S" End Get End Property // Visual C# override public string ID { get { return this.m_owner + "-S";
This code introduces the keywords Me and this. The Me and this keywords refer to the class instance. In this case using Me or this is not required. You could simply type m_owner. You use a keyword in situations in which you might have variable name collisions. Perhaps you have the same field declared in the class and in the method. This keyword indicates which variable to use. You also use the Me and this keywords if you need to pass a reference to the instance to another method. For example, suppose you had a method that took a Form as a parameter: Visual Basic Public Sub MakeFormBlue(aForm As Form) // Visual C# public void MakeFormBlue(Form aForm) You would make this call from within a form s code, like this: Visual Basic MakeFormBlue(Me) // Visual C# MakeFormBlue(this); Adding the Constructor Constructors aren t inherited, so you must add them to the derived class. Also, whenever a constructor is defined, it includes an implicit call to the parameterless constructor that belongs to the base class. In the BankAccount class, you created only one public constructor, and that constructor had one parameter for the owner s name. Because that parameterless constructor doesn t exist in the base class, you need to make an explicit call to the constructor that does exist. Add this constructor for the SavingsAccount class. If you re using Visual C#, you need to delete the constructor without parameters.
Visual Basic Public Sub New(ByVal owner As String) MyBase.New(owner) End Sub // Visual C# public SavingsAccount(string owner) : base(owner) { } The error message about the constructor is now resolved. This code introduces the MyBase and base keywords. MyBase and base refer to the base class of a class. In the case of the constructor, there s no sense in rewriting the code that you wrote in the base class, BankAccount. A call to the base class is sufficient. C# provides a syntax for calling base class members of the same name, : base(). Unlike the Me keyword, MyBase doesn t refer to any instance, so it can t be passed to methods that require an instance reference. Add the Interest property and the AddInterest method 1. Add this code for the Interest property: 2. Visual Basic 3. Private m_interest As Decimal = 0.01D 4. Public Property Interest() As Decimal 5. Get 6. Return m_interest 7. End Get 8. Set(ByVal Value As Decimal) 9. m_interest = Value 10. End Set 11. End Property 12. 13. // Visual C# 14. private decimal m_interest = 0.01M; 15. public decimal Interest { 16. get { 17. return m_interest; 18. } 19. set { 20. m_interest = value; 21. } } 22. Add this code for the AddInterest method: 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. } // Visual C# public decimal AddInterest() { this.Deposit(m_interest * this.Balance); return this.Balance; Visual Basic Public Function AddInterest() As Decimal Me.Deposit(m_interest * Me.Balance) Return Me.Balance End Function
The m_balance field is private to the base class, BankAccount, and the Balance property is read-only. Therefore the only way to add money to the account is, by design, through the Deposit method. You have completed the implementation of the SavingsAccount class. You can now write some test code. Test the SavingsAccount class 1. Open Form1 in the code editor. 2. Delete the code that you added to test the BankAccount class, so that the Form1_Load method is empty. 3. Add this code to test the SavingsAccount class: 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 15. 16. // Visual C# 17. private void Form1_Load(object sender, System.EventArgs e) { 18. 19. 20. 21. 22. 23. 24. SavingsAccount savings = new SavingsAccount("Your Name"); savings.Deposit(150M); savings.Withdraw(50M); savings.Interest = 0.05M; savings.AddInterest(); MessageBox.Show( String.Format("{0}: {1:C}", savings.ID, savings.Balance)); Visual Basic Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim savings As SavingsAccount = New SavingsAccount("Your Name") savings.Deposit(150D) savings.Withdraw(50D) savings.Interest = 0.05D savings.AddInterest() MessageBox.Show( _ String.Format("{0}: {1:C}", savings.ID, savings.Balance))
Copyright © OnBarcode.com . All rights reserved.