Class Property Get and Set
Imports System Public Class MainClass Shared Sub Main(ByVal args As String()) Dim time As New CTime3() ' invoke time6 methods time.Second = (time.Second + 1) time.Minute = (time.Minute + 1) time.Hour = (time.Hour + 1) Console.WriteLine( "Hour: " & time.Hour & "; Minute: " & _ time.Minute & "; Second: " & time.Second ) End Sub End Class ' Represents time in 24-hour format and contains properties. Class CTime3 Inherits Object ' declare Integers for hour, minute and second Private mHour As Integer Private mMinute As Integer Private mSecond As Integer ' CTime3 constructor: initialize each instance variable to zero ' and ensure that each CTime3 object starts in consistent state Public Sub New() SetTime(0, 0, 0) End Sub ' New ' CTime3 constructor: ' hour supplied, minute and second defaulted to 0 Public Sub New(ByVal hourValue As Integer) SetTime(hourValue, 0, 0) End Sub ' New ' CTime3 constructor: ' hour and minute supplied; second defaulted to 0 Public Sub New(ByVal hourValue As Integer, _ ByVal minuteValue As Integer) SetTime(hourValue, minuteValue, 0) End Sub ' New ' CTime3 constructor: hour, minute and second supplied Public Sub New(ByVal hourValue As Integer, _ ByVal minuteValue As Integer, ByVal secondValue As Integer) SetTime(hourValue, minuteValue, secondValue) End Sub ' New ' CTime3 constructor: another CTime3 object supplied Public Sub New(ByVal timeValue As CTime3) SetTime(timeValue.mHour, timeValue.mMinute, _ timeValue.mSecond) End Sub ' New ' set new time value using universal time; ' uses properties to perform validity checks on data Public Sub SetTime(ByVal hourValue As Integer, _ ByVal minuteValue As Integer, ByVal secondValue As Integer) Hour = hourValue ' looks Minute = minuteValue ' dangerous Second = secondValue ' but it is correct End Sub ' SetTime ' property Hour Public Property Hour() As Integer ' return mHour value Get Return mHour End Get ' set mHour value Set(ByVal value As Integer) If (value >= 0 AndAlso value < 24) Then mHour = value Else mHour = 0 End If End Set End Property ' Hour ' property Minute Public Property Minute() As Integer ' return mMinute value Get Return mMinute End Get ' set mMinute value Set(ByVal value As Integer) If (value >= 0 AndAlso value < 60) Then mMinute = value Else mMinute = 0 End If End Set End Property ' Minute ' property Second Public Property Second() As Integer ' return mSecond value Get Return mSecond End Get ' set mSecond value Set(ByVal value As Integer) If (value >= 0 AndAlso value < 60) Then mSecond = value Else mSecond = 0 End If End Set End Property ' Second End Class
1. | Declare Protected Properties | ||
2. | Shared Property Demo | ||
3. | Get and set Properties | ||
4. | Property Shadow during Inheritance | ||
5. | Define and use Class: Property | ||
6. | Compare int property |