8.5 Copy ConstructorsA copy constructor creates a new object by copying variables from an existing object of the same type. For example, you might want to pass a Time object to a Time constructor so that the new Time object has the same values as the old one. VB.NET does not provide a copy constructor, so if you want one you must provide it yourself. Such a constructor copies the elements from the original object into the new one: Public Sub New(ByVal existingObject As Time) Year = existingObject.Year Month = existingObject.Month Date = existingObject.Date Hour = existingObject.Hour minute = existingObject.Minute second = existingObject.Second End Sub A copy constructor is invoked by instantiating an object of type Time and passing it the name of the Time object to be copied : Dim t2 As New Time(existingObject) Here an existing Time object (existingObject) is passed as a parameter to the copy constructor which will create a new Time object ( ), as shown in Example 8-7. Example 8-7. Copy constructorOption Strict On Imports System Public Class Time ' Private variables Private Year As Integer Private Month As Integer Private Date As Integer Private Hour As Integer Private Minute As Integer Private Second As Integer = 30 ' Public methods Public Sub DisplayCurrentTime( ) System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", _ Month, Date, Year, Hour, Minute, Second) End Sub 'DisplayCurrentTime Public Sub New( _ ByVal theYear As Integer, _ ByVal theMonth As Integer, _ ByVal theDate As Integer, _ ByVal theHour As Integer, _ ByVal theMinute As Integer) Year = theYear Month = theMonth Date = theDate Hour = theHour Minute = theMinute Second = theSecond End Sub Public Sub New(existingObject As Time) Year = existingObject.Year Month = existingObject.Month Date = existingObject.Date Hour = existingObject.Hour Minute = existingObject.Minute Second = existingObject.Second End Sub End Class 'Time Module Module1 Sub Main( ) Dim timeObject As New Time(2005, 3, 25, 9, 35) Dim t2 As New Time(timeObject) timeObject.DisplayCurrentTime( ) t2.DisplayCurrentTime( ) End Sub End Module Output: 3/25/2005 9:35:30 3/25/2005 9:35:30 |