×

VB.Net Programs

VB.Net program to demonstrate the constructor chaining

By Nidhi Last Updated : November 11, 2024

Constructor chaining in VB.Net

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

Program/Source Code:

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

VB.Net code to demonstrate the example of constructor chaining

'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
Press any key to continue . . .

Explanation:

In the above program, we created a module Module1. Here, we created a class Sample that contains a data member num. The Sample class contains no argument, parameterized constructor, and a Print() method.

Here we called the default constructor from the parameterized constructor using the Me keyword from the parameterized constructor.

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

VB.Net Basic Programs »


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.