Advertisement
NAK

Polymorphism (VB.NET)

NAK
Dec 5th, 2013
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 2.10 KB | None | 0 0
  1. Module Module1
  2.  
  3.     Sub Main()
  4.         ' Create some objects
  5.         Dim dObj() = New DrawingObject(1) {}
  6.  
  7.         dObj(0) = New Circle(50)
  8.         dObj(1) = New Square(10, 10)
  9.  
  10.         For Each drawObj As DrawingObject In dObj
  11.  
  12.             Select Case drawObj.GetType().Name
  13.                 Case "Circle"
  14.                     Dim circle As Circle = DirectCast(drawObj, Circle)
  15.                     Console.WriteLine(String.Format("I'm a {0} with area of {1} derived from {2}", circle.Draw(), circle.Area(), circle.DrawBase()))
  16.                 Case "Square"
  17.                     Dim square As Square = DirectCast(drawObj, Square)
  18.                     Console.WriteLine(String.Format("I'm a {0} with area of {1} derived from {2}", square.Draw(), square.Area(), square.DrawBase()))
  19.             End Select
  20.  
  21.         Next
  22.     End Sub
  23.  
  24.     Public MustInherit Class DrawingObject
  25.     ' Area() function must be over ridden in derived classes to provide specific functionality
  26.         Public MustOverride Function Area() As Double
  27.     ' DrawBase() function is available from all derived classes
  28.         Public Function DrawBase() As String
  29.             Return "DrawingObject"
  30.         End Function
  31.  
  32.     End Class
  33.  
  34.     Public Class Square
  35.         Inherits DrawingObject
  36.  
  37.         Public Property Width() As Integer
  38.         Public Property Length() As Integer
  39.  
  40.         Public Sub New(w As Integer, l As Integer)
  41.             width = w
  42.             length = l
  43.         End Sub
  44.  
  45.         Public Function Draw() As String
  46.             Return "Square"
  47.         End Function
  48.  
  49.         Public Overrides Function Area() As Double
  50.             Return Width * Length
  51.         End Function
  52.     End Class
  53.  
  54.     Public Class Circle
  55.         Inherits DrawingObject
  56.  
  57.         Public Property Radius() As Integer
  58.  
  59.         Public Sub New(r As Integer)
  60.             Radius = r
  61.         End Sub
  62.  
  63.         Public Function Draw() As String
  64.             Return "Circle"
  65.         End Function
  66.  
  67.         Public Overrides Function Area() As Double
  68.             Return (Math.Pow(Radius, 2) * Math.PI)
  69.         End Function
  70.     End Class
  71.  
  72. End Module
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement