Contributed by Chris Rathman
Module Polymorph
Sub Main()
' create some shape instances
Dim i
Dim scribble(2) As Shape
scribble(0) = New Rectangle(10, 20, 5, 6)
scribble(1) = New Circle(15, 25, 8)
' iterate through the list and handle shapes polymorphically
For i = 0 To UBound(scribble) - 1
scribble(i).draw()
scribble(i).rMoveTo(100, 100)
scribble(i).draw()
Next
' call a rectangle specific function
Dim rect As New Rectangle(0, 0, 15, 15)
rect.setWidth(30)
rect.draw()
End Sub
End Module
|
Public Class Shape
Private x
Private y
' constructor
Public Sub New(ByVal newx, ByVal newy)
setX(newx)
setY(newy)
End Sub
' accessors for x & y coordinates
Public Function getX()
getX = x
End Function
Public Function getY()
getY = y
End Function
Public Sub setX(ByVal newx)
x = newx
End Sub
Public Sub setY(ByVal newy)
y = newy
End Sub
' move the x & y coordinates
Public Sub moveTo(ByVal newx, ByVal newy)
setX(newx)
setY(newy)
End Sub
Public Sub rMoveTo(ByVal deltax, ByVal deltay)
moveTo(deltax + getX(), deltay + getY())
End Sub
' virtual routine - draw the shape
Public Overridable Sub draw()
End Sub
End Class
|
Public Class Rectangle : Inherits Shape
Private width As Integer
Private height As Integer
' constructor
Public Sub New(ByVal newx, ByVal newy, ByVal newwidth, ByVal newheight)
MyBase.New(newx, newy)
setWidth(newwidth)
setHeight(newheight)
End Sub
' accessors for width & height
Public Function getWidth()
getWidth = width
End Function
Public Function getHeight()
getHeight = height
End Function
Public Sub setWidth(ByVal newwidth)
width = newwidth
End Sub
Public Sub setHeight(ByVal newheight)
height = newheight
End Sub
' draw the rectangle
Public Overrides Sub draw()
Console.WriteLine("Drawing a Rectangle at:({0},{1}), Width {2}, Height {3}", _
getX(), getY(), getWidth(), getHeight())
End Sub
End Class
|
Public Class Circle : Inherits Shape
Private radius
' constructor
Public Sub New(ByVal newx, ByVal newy, ByVal newradius)
MyBase.New(newx, newy)
setRadius(newradius)
End Sub
' accessors for the radius
Public Function getRadius()
getRadius = radius
End Function
Public Sub setRadius(ByVal newradius)
radius = newradius
End Sub
' draw the circle
Public Overrides Sub draw()
Console.WriteLine("Drawing a Circle at:({0},{1}), Radius {2}", _
getX(), getY(), getRadius())
End Sub
End Class
|
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 |