- A class is a user-defined data type.
- It is the base of object-oriented programming language.
- A class contains variable and methods inside its body.
Defining a Class
Class is defined using the keyword class. The syntax for defining a class in VB.NET is as follows:
Adding Variables to a Class
- Data is encapsulated in a class by putting data fields inside the body of a class.
- The syntax for declaring variables in class is as follows:
- You can declare any number of variables in a class.
Access-modifier data-type variable1
Access-modifier data-type variable2
Adding Methods to a Class
- Methods are used to perform the operations on the variables. A method may or may not return a value.
- A method which returns a value is called a function.
- A method that does not return any value is called a sub-procedure.
- The syntax for declaring a Function is as follows:
In the above syntax access-modifier are used to define the scope of the function inside the program. We will study about the access-modifier in next chapter. Parameter-list is representing the list of parameter the Function accepts. Type is representing the data-type of value returned by the Function.
The syntax for declaring a sub-procedure is as follows:
Here is an example of definition of class having variables and methods defined inside its body:
Private a As Integer=2
Private b As Integer=3
Private c As Integer
Public Sub add()
- Object is instance of class which can access all the members of class.
- A class is an abstract concept means it is not exist in really but object is a realistic concept which contains all properties of the class. For example if vegetable is a class then potato, leady-finger, bringle etc are its object.
- The actual instance of class is created by making its objects.
- All objects of the class have their own copies of variables and method defined in the class.
- The syntax for declaring an object in VB.NET 2010 is as follows:
After creating an object of class we can access the member of class through the object. The syntax for accessing the members of class through the object is as follows:
Here is an example of VB.NET Classes and Object:
Class addition 'class definition
'declaring variable in class
Private a As Integer = 2
Private b As Integer = 3
Private c As Integer
'declaring sub-procedure in class
Public Sub add(ByVal a As Integer, ByVal b As Integer)
c = a + b
Console.WriteLine("Addition is=" & c)
Dim obj1 As New addition() 'creating object of class
obj1.add(4, 5) 'access member method using object
The output of the above program is given below: