Constructors and Destructors

  • Constructors are the special methods that lets you configure the objects when you create them from a class
  • Constructors can never return a value and can be overridden to provide custom initialization functionality
  • A constructor can also contain calls to other methods
How to add a constructor to a class?
  • You add a Sub procedure named New. You can also declare a constructor which takes the values to it.
Public Class Form1
Dim o1 As New dataclass()
Dim o2 As New dataclass(7)
Public Class dataclass
Private value As Integer
Public Sub New()
End Sub
Public Sub New(ByVal newValue As Integer)
value = newValue
End Sub
Public Function getdata() As Integer
Return value
End Function
End Class
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(o1.getdata())
End Sub
Private Sub Button2_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button2.Click
MsgBox(o2.getdata())
End Sub
End Class
  • A destructor is the last method run by class. A destructor contains code to clean up when a class is destroyed. When a object goes out of scope .NET Frameworks automatically call the finalize method
  • A finalizer in VB.NET is always Sub Finalize().
  • But we can also create our destructors and it is called when an object is no longer needed
Example::
Public Class Form1 Dim object1 As New class1()
Public Class class1
Protected Overrides Sub finalize()
Beep()
End Sub
Public Sub disp()
MessageBox.Show("Hello")
End Sub
End Class
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load object1.disp()
End Sub
End Class


Note: When the Form is closed the finalize( )method is called automatically.

Scope and Access Levels
  • Access levels define how types are instantiated and how members are accessed. The access levels are used to encapsulate data and methods in the types and to expose functionality to outside objects.

What is Classes? << Previous
Next >> Member Access Modifiers and their effect

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus




Footer1