Share via


Visual Basic: Shapes - Areas + Volumes

 This is the source code for this example program: here

This is an Area Calculator for 2D shapes + a Surface Area + Volume Calculator for 3D shapes, that uses Classes + Inheritance. 

This is the Base Class, Shape, which both 2D shapes + 3D shapes inherit:

Public MustInherit Class Shape

    Private ShapeName As String

    Public Sub New(ByVal shape As String)
        ShapeName = shape
    End Sub 

    Public ReadOnly Property shape() As String
        Get
            Return ShapeName
        End Get
    End Property 

    Public Overrides Function ToString() As String
        Return String.Format("Shape: {0}", ShapeName)
    End Function 

End Class

It has just 1 String property, shape, which is ReadOnly + set in the constructor, + has an overridden ToString Function which returns the first part of the program’s eventual output.

 

This is the MustInherit twoDimensional Class, which is inherited by Square + Circle shapes:

Public MustInherit Class twoDimensional
    Inherits Shape

    Private xSideValue As Decimal
    Private ySideValue As Decimal
    Private RadiusValue As Decimal 

    Public Sub New(ByVal shape As String, ByVal xSide As Decimal, ByVal ySide As Decimal, ByVal Radius As Decimal)
        MyBase.New(shape)
        Me.xSide = xSide
        Me.ySide = ySide
        Me.Radius = Radius
    End Sub 

    Public Property xSide() As Decimal
        Get
            Return xSideValue
        End Get
        Set(ByVal value As Decimal)
            If value >= -1D Then
                xSideValue = value
            Else
                Throw New ArgumentOutOfRangeException("side must be greater than or equal to 0 or -1 (unused)")
            End If
        End Set
    End Property 

    Public Property ySide() As Decimal
        Get
            Return ySideValue
        End Get
        Set(ByVal value As Decimal)
            If value >= -1D Then
                ySideValue = value
            Else
                Throw New ArgumentOutOfRangeException("side must be greater than or equal to 0 or -1 (unused)")
            End If
        End Set
    End Property 

    Public Property Radius() As Decimal
        Get
            Return RadiusValue
        End Get
        Set(ByVal value As Decimal)
            If value >= -1D Then
                RadiusValue = value
            Else
                Throw New ArgumentOutOfRangeException("Radius must be greater than or equal to 0 or -1 (unused)")
            End If
        End Set
    End Property 

    Public Overrides Function ToString() As String
        Return String.Format("{0}{4}{4}{1}{2}{3}", MyBase.ToString(), _
                             If(Me.xSide <> -1, String.Format("x Side: {0}cm{1}", Me.xSide, Environment.NewLine), ""), _
                             If(Me.ySide <> -1, String.Format("y Side: {0}cm{1}", Me.ySide, Environment.NewLine), ""), _
                             If(Me.Radius <> -1, String.Format("Radius: {0}cm{1}", Me.Radius, Environment.NewLine), ""), _
                             Environment.NewLine)
    End Function 

    Public MustOverride Function GetArea() As String 

End Class

 

It has 3 properties, xSide, ySide, + Radius. These 3 properties are set in the constructor, where the Base Class Shape property is also set. This class also has an overridden ToString Function which returns the second part of the program’s eventual output.

This Class has a MustOverride Function which both derived Classes must override.

The threeDimensional Class is very similar, except the Radius Property doubles as the z value Property for cuboids and the class has 2 MustOverride Functions which again both derived Classes must override.

 

This is the derived Square Class:

 

Public Class Square
    Inherits twoDimensional 

    Public Sub New(ByVal xSize As Decimal, ByVal ySize As Decimal)
        MyBase.New("Square", xSize, ySize, -1)
    End Sub 

    Public Overrides Function GetArea() As String
        Return (Me.xSide * Me.ySide).ToString("f3").Replace(".000", "")
    End Function 

    Public Overrides Function ToString() As String
        Return String.Format("{0}{2}Area: {1}cm²", MyBase.ToString, GetArea, Environment.NewLine)
    End Function 

End Class

 

It inherits twoDimensional, has a constructor where the shape type + size is set, has an overridden ToString Function which forms the final part of the program’s output, + overrides the MustOverride GetArea Function from the twoDimensional class.

The derived Circle Class is very similar except in its constructor + in the formula it uses in the GetArea Function.

 

This is the derived Sphere Class:

 

Public Class Sphere
    Inherits threeDimensional 

    Public Sub New(ByVal zRadius As Decimal)
        MyBase.New("Sphere", -1, -1, zRadius)
    End Sub 

    Public Overrides Function GetSurfaceArea() As String
        Return CDec(4 * Math.PI * Me.Radius ^ 2).ToString("f3").Replace(".000", "")
    End Function 

    Public Overrides Function GetVolume() As String
        Return CDec((4 / 3) * Math.PI * Me.Radius ^ 3).ToString("f3").Replace(".000", "")
    End Function 

    Public Overrides Function ToString() As String
        Return String.Format("{0}{3}{3}Surface Area: {1}cm²{3}Volume: {2}cm³", MyBase.ToString, GetSurfaceArea, GetVolume, Environment.NewLine)
    End Function 

End Class

 

It inherits threeDimensional, has a constructor where the shape type + size is set, has an overridden ToString Function which forms the final part of the program’s output, + overrides the MustOverride GetSurfaceArea Function + the MustOverride GetVolume Function from the threeDimensional class.

The derived Cube Class is very similar except in its constructor + in the formulas it uses in the GetSurfaceArea Function + the GetVolume Function.

 

The final part of this program is the Form. This is the code:

 

Public Class Form1 

    Private shapeName As String = "Square" 

    Private Sub SquareToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SquareToolStripMenuItem.Click, SphereToolStripMenuItem.Click, CubeToolStripMenuItem.Click, CircleToolStripMenuItem.Click

        Dim mi As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        If mi.Checked Then
            SquareToolStripMenuItem.Checked = False
            CircleToolStripMenuItem.Checked = False
            CubeToolStripMenuItem.Checked = False
            SphereToolStripMenuItem.Checked = False
            mi.Checked = True
        End If 

        Select Case mi.Text
            Case "Square"
                TextBox1.Enabled = True
                TextBox2.Enabled = True
                TextBox3.Clear()
                TextBox3.Enabled = False
                Button1.Text = "Get Area"
            Case "Circle"
                TextBox1.Clear()
                TextBox2.Clear()
                TextBox1.Enabled = False
                TextBox2.Enabled = False
                Label3.Text = "r"
                TextBox3.Enabled = True
                Button1.Text = "Get Area"
            Case "Cube"
                TextBox1.Enabled = True
                TextBox2.Enabled = True
                Label3.Text = "z"
                TextBox3.Enabled = True
                Button1.Text = "Get Surface Area && Volume"
            Case "Sphere"
                TextBox1.Clear()
                TextBox2.Clear()
                TextBox1.Enabled = False
                TextBox2.Enabled = False
                Label3.Text = "r"
                TextBox3.Enabled = True
                Button1.Text = "Get Surface Area && Volume"
        End Select 

        shapeName = mi.Text

        Me.Text = "Shapes: " & shapeName 

    End Sub

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Select Case shapeName
            Case "Square"
                Dim x, y As Decimal
                If Decimal.TryParse(TextBox1.Text, x) AndAlso Decimal.TryParse(TextBox2.Text, y) Then
                    Dim s As New Square(x, y)
                    MsgBox(s.ToString)
                End If
            Case "Circle"
                Dim r As Decimal
                If Decimal.TryParse(TextBox3.Text, r) Then
                    Dim c As New Circle(r)
                    MsgBox(c.ToString)
                End If
            Case "Cube"
                Dim x, y, z As Decimal
                If Decimal.TryParse(TextBox1.Text, x) AndAlso Decimal.TryParse(TextBox2.Text, y) AndAlso Decimal.TryParse(TextBox3.Text, z) Then
                    Dim cb As New Cube(x, y, z)
                    MsgBox(cb.ToString)
                End If
            Case "Sphere"
                Dim r As Decimal
                If Decimal.TryParse(TextBox3.Text, r) Then
                    Dim sp As New Sphere(r)
                    MsgBox(sp.ToString)
                End If
        End Select

    End Sub 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Dim parts() As String = Environment.GetCommandLineArgs.Skip(1).ToArray
        'If parts.Length = 0 OrElse String.Join(" ", parts) <> "Maths Revision V2.0" Then End

    End Sub

 

    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

        For c As Integer = 0 To Me.Width Step 25
            e.Graphics.DrawLine(Pens.LightGray, c, 0, c, Me.Height)
        Next
        For r As Integer = 0 To Me.Height Step 25
            e.Graphics.DrawLine(Pens.LightGray, 0, r, Me.Width, r)
        Next

    End Sub 

End Class

 

Most of the code handles the Shape selector Menustrip.

The Button1_Click event creates new Classes based on sizes the user inputs in the TextBoxes+ displays the output from those Classes in MessageBoxes.

This example was written in vb2008 (with Option Strict On), but there is nothing in it that won’t convert to vb2010 or vb2012.