Lab 4: Using Inherited Classes

Lab 4: Using Inherited Classes

In this lab, you will learn to create inherited classes. You will extend the Fraction class from Lab 3-2 and create a CompoundFraction class that allows the user to initialize the class with a fraction and a whole number, and displays the value of the fraction as a compound fraction. You will then create an overloaded operator (with Visual C#) or implement an Add method (with Visual Basic) to add two Fraction objects together. Finally, you will create a strongly typed collection class that manages a collection of Fraction instances. The solution to this lab is available on the Supplemental Course Materials CD-ROM in the \Labs\Ch04\Solution folder

Before You Begin

You should have completed Lab 3-2, or loaded the Lab 3-2 solution from the Supplemental Course Materials CD-ROM.

Estimated lesson time: 45 minutes

Exercise 4.1: Creating the CompoundFraction Class

In this exercise, you will create the CompoundFraction class by inheriting from the Fraction class and providing additional functionality. You will add an additional constructor that allows the user to specify a whole number in addition to a numerator and denominator when initializing. You will also implement an overridden ToString method that displays the value represented by the fraction as a whole number and fraction, rather than just as a fraction.

To create the CompoundFraction class

  1. In the designer, choose Add Class from the Project menu. The Add New Item dialog box opens. Name your class CompoundFraction and click ok. The new class is added to your project, and the code window opens.

  2. In the code window, specify that your class inherits the Fraction class. This is done by using the Inherits keyword (in Visual Basic .NET), or by using the : operator in the class declaration (in Visual C#) as shown below:

    Visual Basic .NET

    Public Class CompoundFraction Inherits Fraction End Class

    Visual C#

    using System; namespace Lab4CSharp { /// <summary> /// Summary description for CompoundFraction. /// </summary> public class CompoundFraction : Fraction { public CompoundFraction() { // // TODO: Add constructor logic here // } } }

  3. Add a constructor (Visual Basic .NET) or modify the provided constructor (Visual C#) to initialize the class. This constructor should accept a value for the numerator and denominator, and pass those values to the base class constructor. An example is shown:

    Visual Basic .NET

    Public Sub New(ByVal Numerator As Integer, _ ByVal Denominator As Integer) MyBase.New(Numerator, Denominator) End Sub

    Visual C#

    public CompoundFraction(int Numerator, int Denominator) : base(Numerator, Denominator) { }

  4. Add an additional constructor that allows the user to specify a whole number in addition to the numerator and denominator. Since you must make a call to the constructor of the base class, you should convert the whole number parameter to the numerator equivalent before calling the base class constructor. Your finished constructor should look like the example:

    Visual Basic .NET

    Public Sub New(ByVal Numerator As Integer, ByVal Denominator As _ Integer, ByVal WholeNumber As Integer) MyBase.New(Numerator + (WholeNumber * Denominator), Denominator) End Sub

    Visual C#

    public CompoundFraction(int Numerator, int Denominator, int WholeNumber) : base(Numerator + (WholeNumber * Denominator), Denominator) { }

  5. Add a third constructor that allows the user to create a new CompoundFraction instance from an existing Fraction instance. This constructor should pass the Numerator and Denominator of the supplied Fraction instance to the base constructor. An example follows.

    Visual Basic .NET

    Public Sub New(ByVal f As Fraction) MyBase.New(f.Numerator, f.Denominator) End Sub

    Visual C#

    public CompoundFraction(Fraction f) : base(f.Numerator,f.Denominator) { }

  6. Override the ToString method to provide a new implementation that returns a string that represents the value of the CompoundFraction class instance, but returns a whole number and a fraction when appropriate instead of simply the numerator over the denominator. When finished, your ToString method should look something like the example shown below:

    Visual Basic .NET

    Public Overrides Function ToString() As String Dim Result As String Dim tempNumerator As Integer = Numerator Dim wholenumber As Integer = 0 ' This loop reduces the fraction to its compound representation Do While tempNumerator >= Denominator tempNumerator -= Denominator wholenumber += 1 Loop ' Determines if there is a whole number component If Not wholenumber = 0 Then Result = wholenumber.ToString End If ' Determines if there is a fractional component If Not tempNumerator = 0 Then If Not wholenumber = 0 Then Result &= " " Result &= tempNumerator.ToString & "/" & Denominator.ToString End If Return Result End Function

    Visual C#

    public override string ToString() { string Result = ""; int tempNumerator = Numerator; int wholenumber = 0; // This loop reduces the fraction to its compound representation while (tempNumerator >= Denominator) { tempNumerator -= Denominator; wholenumber ++; } // Determines if there is a whole number component if (!(wholenumber == 0)) Result = wholenumber.ToString(); // Determines if there is a fractional component if (!(tempNumerator == 0)) { if (!(wholenumber == 0)) Result += " "; Result += tempNumerator.ToString() + "/"  + Denominator.ToString(); } return Result; }

  7. In Solution Explorer, right-click Form1 and choose View Designer. The designer for Form1 opens. From the Toolbox, add a new label and textbox control to the form (you may need to make Form1 larger) and set the text values as shown in Table 4.1.

    Table 4-1. Properties for the New Controls

    Control

    Text Value

    Label7

    Whole number

    TextBox3

    (blank)

  8. In Solution Explorer, right-click Form1 and choose View Code. The code window for Form1 opens. Locate the Button1_Click method, and modify it to create a new CompoundFraction instance instead of a Fraction instance and to check TextBox3 for any input and incorporate it appropriately. The following example demonstrates what your modified code should look like.

    Visual Basic .NET

    Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim numerator As Integer Dim denominator As Integer Dim wholenumber As Integer Dim afraction As CompoundFraction numerator = Integer.Parse(TextBox1.Text) denominator = Integer.Parse(TextBox2.Text) If Not TextBox3.Text = "" Then wholenumber = Integer.Parse(TextBox3.Text) afraction = New CompoundFraction(numerator, denominator, _ wholenumber) Else afraction = New CompoundFraction(numerator, denominator) End If Label4.Text = afraction.ToString Label6.Text = afraction.ToDouble Catch ex As Exception MessageBox.Show("Please check the values and try again!") End Try End Sub

    Visual C#

    private void button1_Click(object sender, System.EventArgs e) { try { int numerator; int denominator; int wholenumber; CompoundFraction aFraction; numerator = int.Parse(textBox1.Text); denominator = int.Parse(textBox2.Text); if (!(textBox3.Text == "")) { wholenumber = int.Parse(textBox3.Text); aFraction = new CompoundFraction(numerator, denominator, wholenumber); } else { aFraction = new CompoundFraction(numerator, denominator); } label4.Text = aFraction.ToString(); label6.Text = (aFraction.ToDouble()).ToString(); } catch { MessageBox.Show("Please check the values and try again!"); } }

  9. Press F5 to build and run your application. Test your new CompoundFraction class with a variety of values for each entry. Note that the ToString method now displays the value as a compound fraction instead of a simple fraction.

Exercise 4.2: Creating Overloaded Operators or Shared Methods

In this exercise, you will implement functionality that allows you to add two instances of the CompoundFraction class. For Visual C#, you will implement and overloaded + operator. For Visual Basic .NET. you will implement a Shared Add method.

To implement the Add functionality

  1. In Solution Explorer, right-click Fraction and choose View Code. The Code window opens.

    In the Code editor, add the following overloaded operator/method:

    Visual Basic .NET

    Public Shared Function Add(ByVal fraction1 As Fraction, _ ByVal fraction2 As Fraction) As Fraction Dim tempDenominator As Integer Dim tempNumerator1 As Integer Dim tempNumerator2 As Integer Dim Result As Fraction tempDenominator = fraction1.Denominator * fraction2.Denominator tempNumerator1 = fraction1.Numerator * fraction2.Denominator tempNumerator2 = fraction2.Numerator * fraction1.Denominator Result = New Fraction(tempNumerator1 + tempNumerator2, _ tempDenominator) Result.Reduce() Return Result End Function

    Visual C#

    public static Fraction operator +(Fraction fraction1, Fraction fraction2) { int tempDenominator; int tempNumerator1; int tempNumerator2; Fraction Result; tempDenominator = fraction1.Denominator * fraction2.Denominator; tempNumerator1 = fraction1.Numerator * fraction2.Denominator; tempNumerator2 = fraction2.Numerator * fraction1.Denominator; Result = new Fraction(tempNumerator1 + tempNumerator2, tempDenominator); return Result; }

  2. From the Build menu, choose Build Solution to build and save your work. You will test this functionality in the next exercise.

Exercise 4.3: Creating a Strongly Typed Collection Class

In this exercise, you will create a strongly typed collection class by inheriting from the CollectionBase class. Your new collection class will accept only Fraction objects, and will include methods to add and remove a Fraction to and from the collection, as well as functionality to access each member of the collection by its index. Finally, you will implement a method that returns the total of all Fraction objects contained in the collection.

To create the strongly typed collection

  1. From the Project menu, choose Add Class. The Add New Item dialog box opens. Name this new class FractionCollection.

  2. Inherit from the CollectionBase class to provide a basic core of collection-type functionality to your new class. An example is shown below:

    Visual Basic .NET

    Public Class FractionCollection Inherits CollectionBase End Class

    Visual C#

    public class FractionCollection : System.Collections.CollectionBase

  3. Implement an Add method that allows the user to add a Fraction instance to the collection. You should do this by creating a method that can accept only a Fraction instance, and calls the Add method of the internal List object of CollectionBase. An example is shown:

    Visual Basic .NET

    Public Sub Add(ByVal f As Fraction) List.Add(f) End Sub

    Visual C#

    public void Add(Fraction f) { List.Add(f); }

  4. Implement a Remove method that removes a particular Fraction instance from the collection. You can implement this functionality by passing the method parameter to the Remove method of the internal List object, as shown below:

    Visual Basic .NET

    Public Sub Remove(ByVal f As Fraction) List.Remove(f) End Sub

    Visual C#

    public void Remove(Fraction f) { List.Remove(f); }

  5. Implement a default property (Visual Basic .NET) or indexer (Visual C#) that takes an integer parameter as an index and returns or sets the object that is located at that index. An example is shown below:

    Visual Basic .NET

    Default Public Property Item(ByVal I As Integer) As Fraction Get Return CType(List.Item(I), Fraction) End Get Set(ByVal Value As Fraction) List.Item(I) = Value End Set End Property

    Visual C#

    public Fraction this[int i] { get { return (Fraction)List[i]; } set { List[i] = value; } }

  6. Implement a method that returns the total of all Fraction objects contained in the collection. This method should use the Shared Fraction.Add method (for Visual Basic .NET) or the overloaded + operator (for Visual C#). For example:

    Visual Basic .NET

    Public Function Total() As Fraction Dim Result as Fraction If Me.Count = 0 Then Result = New Fraction(0,1) Else If Me.Count = 1 Then Result = Me.Item(0) Else Result = Me.Item(0) Dim Counter As Integer For Counter = 1 to Me.Count -1 Result = Fraction.Add(Result, Me.Item(Counter)) Next End If Return Result End Function

    Visual C#

    public Fraction Total() { Fraction Result; if (this.Count == 0) { Result = new Fraction(0,1); } else if (this.Count == 1) { Result = this[0]; } else { Result = this[0]; int Counter; for(Counter = 1; Counter < this.Count; Counter ++) { Result = Result + this[Counter]; } } return Result; } 

  7. In Solution Explorer, right-click Form1 and choose View Designer. From the Toolbox, add three buttons to the form (you may need to make Form1 larger). When finished, your form should look similar to Figure 4.1. Set the Text property of the buttons as shown in Table 4.2.

    figure 4-1 the test form.

    Figure 4-1. The Test form.

    Table 4-2. Text Property of New Buttons

    Button

    Text

    Button2

    Add To Collection

    Button3

    Display Total

    Button4

    Clear Collection

  8. In Solution Explorer, right-click Form1 and choose View Code. The Code Editor opens. Add a line of code, within the class member declaration section, to declare and instantiate a new instance of the FractionCollection class, as shown below.

    Visual Basic .NET

    Private myFractions As New FractionCollection

    Visual C#

    private FractionCollection myFractions = new FractionCollection();

  9. In Solution Explorer, right-click Form1 to return to the designer. Double-click Button2, the Add to Collection button, to create an event handler for that button s Click event. Add code to this method that creates a new fraction from the values in the textboxes and adds that fraction to the fraction collection, then clears the textboxes. An example is shown below. Note that the code is very similar to the code you provided for Button1.Click.

    Visual Basic .NET

    Private Sub Button2_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button2.Click Try Dim numerator As Integer Dim denominator As Integer Dim wholenumber As Integer Dim afraction As Fraction numerator = Integer.Parse(TextBox1.Text) denominator = Integer.Parse(TextBox2.Text) If Not TextBox3.Text = "" Then wholenumber = Integer.Parse(TextBox3.Text) afraction = New Fraction(numerator, denominator, _ wholenumber) Else afraction = New Fraction(numerator, denominator) End If myFractions.Add(afraction) TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = ""  Catch ex As Exception MessageBox.Show("Please check the values and try again!") End Try End Sub

    Visual C#

    private void button2_Click(object sender, System.EventArgs e) { try { int numerator; int denominator; int wholenumber; Fraction aFraction; numerator = int.Parse(textBox1.Text); denominator = int.Parse(textBox2.Text); if (!(textBox3.Text == "")) { wholenumber = int.Parse(textBox3.Text); aFraction = new Fraction(numerator, denominator, wholenumber); } else { aFraction = new Fraction(numerator, denominator); } myFractions.Add(aFraction); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; } catch { MessageBox.Show("Please check the values and try again!"); } }

  10. Return to the Designer, and double-click Button3, the Display Total button, to generate an event handler for this button s click event. Add a line of code to this method to display the total of the Fraction objects in the collection in a MessageBox, as shown below.

    Visual Basic .NET

    Public Sub Button3_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button3.Click Dim cf As New CompoundFraction(myFractions.Total) MessageBox.Show(cf.ToString) End Sub

    Visual C#

    public void button3_Click(object sender, System.EventArgs e) { CompoundFraction cf = new CompoundFraction(myFractions.Total()); MessageBox.Show(cf.ToString()); }

  11. Return to the Designer, and double-click Button4, the Clear Collection button, to generate an event handler for this button s click event. Add a line of code to this method to clear the FractionCollection, as shown below:

    Visual Basic .NET

    Public Sub Button4_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button4.Click myFractions.Clear() End Sub

    Visual C#

    public void button4_Click(object sender, System.EventArgs e) { myFractions.Clear(); }

  12. Press F5 to build and test your work. Add several different combinations of fractions to the new collection and view the totals. Note that even though you are creating CompoundFraction objects in the application, and the collection is designed to accept Fraction objects, everything works out fine. When a CompoundFraction instance is added to the collection, it behaves polymorphically as a Fraction.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net