Downcast: cast base-class reference to derived-class : Class Cast « Class Module « VB.Net Tutorial

Home
VB.Net Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statements
5.Date Time
6.Class Module
7.Development
8.Collections
9.Generics
10.Attributes
11.Event
12.LINQ
13.Stream File
14.GUI
15.GUI Applications
16.Windows Presentation Foundation
17.2D Graphics
18.I18N Internationlization
19.Reflection
20.Regular Expressions
21.Security
22.Socket Network
23.Thread
24.Windows
25.XML
26.Database ADO.net
27.Design Patterns
VB.Net
VB.Net by API
VB.Net Tutorial » Class Module » Class Cast 
6.35.1.Downcast: cast base-class reference to derived-class
Class Tester

   
   Shared Sub Main()
      Dim point1, point2 As Point
      Dim circle1, circle2 As Circle

      point1 = New Point(3050)
      circle1 = New Circle(120892.7)

      Console.WriteLine("Point point1: " & point1.ToString() & _
         vbCrLf & "Circle circle1: " & circle1.ToString())

      point2 = circle1

      Console.WriteLine("Circle circle1 (via point2): " & point2.ToString())

      circle2 = CType(point2, Circle' allowed only via cast

      Console.WriteLine("Circle circle1 (via circle2): " & circle2.ToString())

      If (TypeOf point1 Is CircleThen
         circle2 = CType(point1, Circle)
         Console.WriteLine("cast successful")
      Else
         Console.WriteLine("point1 does not refer to a Circle")
      End If
   End Sub

End Class 

Public Class Point
   Private mX, mY As Integer

   Public Sub New()
   End Sub ' New

   Public Sub New(ByVal xValue As Integer, _
      ByVal yValue As Integer)
   End Sub ' New
   Public Overrides Function ToString() As String
      Return "[" & mX & ", " & mY & "]"
   End Function ' ToString

End Class

Public Class Circle
   Inherits Point 

   Private mRadius As Double

   Public Sub New()
   End Sub ' New

   Public Sub New(ByVal xValue As Integer, _
      ByVal yValue As Integer, ByVal radiusValue As Double)

      MyBase.New(xValue, yValue)
   End Sub ' New

   Public Overrides Function ToString() As String
      Return "Center= " & MyBase.ToString() & _
         "; Radius = " & mRadius
   End Function ' ToString

End Class
Point point1: [0, 0]
Circle circle1: Center= [0, 0]; Radius = 0
Circle circle1 (via point2): Center= [0, 0]; Radius = 0
Circle circle1 (via circle2): Center= [0, 0]; Radius = 0
point1 does not refer to a Circle
6.35.Class Cast
6.35.1.Downcast: cast base-class reference to derived-class
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.