{ |one, step, back| }

The Shape Example in Visual Basic

Contributed by Csaba Urbaniczky

Code for Visual Basic

File: ShapesMod.vb

'to  http://onestepback.org/articles/poly/ by CsabaU@Hotmail.com

Module ShapesMod

    Class Shape
        Public xPos, yPos As Double ' Could be replaced by properties

        Sub New(ByVal initX As Double, ByVal initY As Double)
            xPos = initX
            yPos = initY
        End Sub

        Sub MoveTo(ByVal newX As Double, ByVal newY As Double)
            xPos = newX
            yPos = newY
        End Sub

        Sub RelativeMoveTo(ByVal relXdiff As Double, ByVal relYdiff As Double)
            xPos += relXdiff
            yPos += relYdiff
        End Sub

        Overridable Sub Draw() ' Write first class name using "reflection" = meta information
            Console.Write("Drawing a " & Me.GetType().Name & " at:(" & xPos & "," & yPos & "). ")
        End Sub
    End Class


    Class Rectangle : Inherits Shape
        Public width, height As Double ' Could be replaced by properties

        ' constructor
        Sub New(ByVal initX As Double, ByVal initY As Double, ByVal initWidth As Double, ByVal initHeight As Double)
            MyBase.new(initX, initY)
            width = initWidth
            height = initHeight
        End Sub

        ' draw the rectangle
        Overrides Sub Draw()
            MyBase.Draw()
            Console.WriteLine("Width " & width & ", height " & height)
        End Sub
    End Class

    Class Circle : Inherits Shape
        Public radius As Double  ' Could be replaced by properties

        ' constructor
        Sub New(ByVal initX As Double, ByVal initY As Double, ByVal initRadius As Double)
            MyBase.new(initX, initY)
            radius = initRadius
        End Sub

        'draw the circle
        Overrides Sub Draw()
            MyBase.Draw()
            Console.WriteLine("Radius " & radius)
        End Sub
    End Class

    Sub Main()
        'create a collection containing various shape instances
        Dim shapes As Shape() = {New Rectangle(10, 20, 5, 6), New Circle(15, 25, 8)}

        ' iterate through the collection and handle shapes polymorphically
        For Each aShape As Shape In shapes
            aShape.Draw()
            aShape.RelativeMoveTo(100, 100)
            aShape.Draw()
        Next

        ' access a rectangle specific function
        Dim aRectangle As Rectangle = New Rectangle(0, 0, 15, 15)
        aRectangle.width = 30
        aRectangle.Draw()

        Console.ReadLine() ' so output will not diseappear at once
    End Sub

End Module

Output

Drawing a Rectangle at:(10,20). Width 5, height 6
Drawing a Rectangle at:(110,120). Width 5, height 6
Drawing a Circle at:(15,25). Radius 8
Drawing a Circle at:(115,125). Radius 8
Drawing a Rectangle at:(0,0). Width 30, height 15