Consider the following class: Public Module Exercise Friend Class Rectangle Public Shared Length As Double Public Shared Height As Double Public Function CalculatePerimeter#() Return (Length + Height) * 2 End Function Public Function CalcaulteArea#() Return Length * Height End Function End Class Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68 Rectangle.Length = 32.47 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Length:" & vbTab & Rectangle.Length & vbCrLf & _ "Height:" & vbTab & Rectangle.Height) Return 0 End Function End Module This would produce: Like member variables, a method can be shared among classes. In some cases, shared methods are more used than shared member variables because a shared method allows performing an action on a class without declaring an instance of that class. To create a shared method, type the Shared keyword on the left of the Sub or the Function keyword. Here is an example: Here is an example: Friend Class Rectangle Shared Function CalculatePerimeter#() Return (Length + Height) * 2 End Function End Class You can apply the access modifier on the method as we have done so far. Here are examples: Friend Class Rectangle Public Shared Function CalculatePerimeter#() End Function Public Shared Function CalcaulteArea#() End Function End Class Like a shared member variable, once a method has been created as shared, it can be accessed directly from anywhere. Remember that you would need to type the name of the class before accessing the method. The name of the class allows you to "qualify" the method. Here is an example: Public Module Exercise Friend Class Rectangle Public Shared Length As Double Public Shared Height As Double Public Shared Function CalculatePerimeter#() Return (Length + Height) * 2 End Function Public Shared Function CalcaulteArea#() Return Length * Height End Function End Class Public Function Main() As Integer REM Notice that a Rectangle variable is not declared Rectangle.Height = 20.68 Rectangle.Length = 32.47 MsgBox("Rectangle Characteristics" & vbCrLf & _ "Length:" & vbTab & vbTab & Rectangle.Length & vbCrLf & _ "Height:" & vbTab & vbTab & Rectangle.Height & vbCrLf & _ "Perimeter: " & vbTab & Rectangle.CalculatePerimeter#() & vbCrLf & _ "Area: " & vbTab & vbTab & Rectangle.CalcaulteArea#()) Return 0 End Function End Module |
|
|||
|