VB.NET tutorial-Class constructors


Object-Oriented Programming (OOP)

Class constructors

Constructor is a special method that can be used to initialize objects of the class when they are created. The constructor is declared with the New keyword.

Example:

Module Module1

 

    Sub Main()

        Dim st As New Student()

        'st.setnumber()

        st.getnumber()

        Console.ReadLine()

    End Sub

 

    Class Student

        Private stnumber As Integer

        Private stname As String

        Private stsex As String

        Sub New()'constructor

            stnumber = 0

        End Sub

 

        Public Sub setnumber()

            Console.WriteLine("Enter student's number:")

            stnumber = CInt(Console.ReadLine)

        End Sub

 

        Public Sub getnumber()

            Console.WriteLine("Student's number is:" & stnumber)

 

        End Sub

    End Class

 

 

End Module

You also can pass parameters through constructor.

Example:

Module Module1

 

    Sub Main()

        Dim st As New Student(1)

        'st.setnumber()

        st.getnumber()

        Console.ReadLine()

    End Sub

 

    Class Student

        Private stnumber As Integer

        Private stname As String

        Private stsex As String

        Sub New(ByVal num As Integer) 'constructor with 1 parameter

            stnumber = num

        End Sub

 

        Public Sub setnumber()

            Console.WriteLine("Enter student's number:")

            stnumber = CInt(Console.ReadLine)

        End Sub

 

        Public Sub getnumber()

            Console.WriteLine("Student's number is:" & stnumber)

 

        End Sub

    End Class

 

 

End


Comments

CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.