Class and Objects in VB.NET

In this article You will learn about Class and Object in VB.NET.
  • 2031

A class means collection of methods/functions. Method/function accepts parameters, process set of codes which you have written in the module/function and returns the output to the caller. Collection of class is called Class Library. When you compile the Class Library it becomes a DLL. A class in VB.Net is declared using the keyword Class and its members are enclosed with the End Class marker. A class is simply an abstract model used to define new data types. A class may contain any combination of encapsulated data (fields or member variables),operations that can be performed on the data (methods) and accessors to data (properties).

The general syntax of a class looks as following:

public Class test
.... Variables
.....methods
.....properties
.....events
End Class

The above syntax created a class named Test. Fields, Properties, Methods, and Events are members of the class. They can be declared as Public, Private, Protected, Friend or Protected Friend. 

Fields and Properties represent information that an object contains. Fields of a class are like variables and they can be read or set directly. For example, if you have an object named House, you can store the numbers of rooms in it in a field named Rooms.

Properties are retrieved and set like fields but are implemented using Property Get and Property Set procedures which provide more control on how values are set or returned.

Methods
represent the object's built-in procedures. For example, a Class named Country may have methods named Area and Population. You define methods by adding procedures, Sub routines or functions to your class. For example, implementation of the Area and Population methods discussed above might look like this

Public Class Country
Public Sub Area()
Write("--------")
End Sub
Public Sub population()
Write("---------")
End Sub
End Class 

OBJECT:

Objects are instance of the class. Classes and Objects are very much related to each other. Without objects you can't use a class. To create a object for this class we use the new keyword and that looks like this: Dim obj as new Test().

The following code defines the Class and Objects in VB.NET:

Module Module1

    Public Class test 'define class test

        Dim a As Integer = 5

        Dim b As Integer = 6

        Dim c As Integer

        Sub add()

            c = a + b

            Console.Write(" addition of two number :=")

            Console.WriteLine(c)

        End Sub

    End Class

    Sub Main()

        Dim obj As New test()

        obj.add() 'creating a Object obj for test class

    End Sub

End Module

In this example test define the Class and obj defines the objects of class test.

Output of above code:

 add.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.