Home >>VB.Net Built-in Functions >VB.Net program to demonstrate the constructor chaining

VB.Net program to demonstrate the constructor chaining

Write a VB.Net program to demonstrate the constructor chaining

Here, to initialize data member, we can create a Sample class containing the default and parameterized constructor, here from the parameterized constructor we called the default constructor.

Program :

The source code to demonstrate the chaining of the constructor is given below. The program given is compiled and successfully executed.

'VB.net program to demonstrate the constructor chaining.


Module Module1
    Class Sample
        Private num As Integer
        Public Sub New()
            Console.WriteLine("Default or no argument constructor called")
        End Sub
        Public Sub New(ByVal n As Integer)
            Me.New()
            Console.WriteLine("Parameterized constructor called")
            num = n
        End Sub
        Public Sub Print()
            Console.WriteLine("Value of num: {0}", num)
        End Sub
    End Class
    Sub Main()
        Dim obj As New Sample(20)
        obj.Print()
    End Sub
End Module
	
Output:
Default or no argument constructor called
Parameterized constructor called
Value of num: 20
Explanation:

We created a Module1 module in the programme above. Here, a class sample containing a data member num has been developed. No argument, parameterized constructor, and the Print() method are included in the Sample class.

Here, we used the Me keyword from the parameterized constructor to call the default constructor from the parameterized constructor

The Main() method is the entry point for the program, where we created a Sample Class object and then printed the data member num value on the screen of the console.


No Sidebar ads