VB.Net - SPLessons

VB.Net Classes and Objects

Home > > Tutorial
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

VB.Net Classes and Objects

VB.Net Classes & Objects

shape Description

Class is a combination of Member Functions (or) Methods and Variables (or) Data Members. An object is an instance of the class. Class don't have the permission to allocate memory. For this reason, i.e to allocate memory and also to access the features of class in main method we have to create an instance for this class, i.e called as an Object.One class may have more objects but to create an object there class should be created.Following is the syntax to create a class and create an object in VB.Net. [vbnet]Access_Specifier Class ClassName 'Data Members or Variables Declaration 'Methods End Class[/vbnet] [vbnet] Dim Object_Name as Class_Name= New Class_Name(); 'Declaration of object Object_Name.Method_Name(); 'Accessing method using the object [/vbnet]

shape Example

Following is an example which describes more about class and object. [vbnet] Class Example 'Class Definition Private a As Integer = 20 Private b As Integer = 20 Public Function AddResult() As Integer Return a + b End Function End Class Module Module1 Sub Main() Dim obj As Example = New Example() 'Object declaration Console.WriteLine("Addition of two numbers is") Console.WriteLine(obj.AddResult()) 'Accessing the function in the class using object Console.ReadKey() End Sub End Module [/vbnet] Output: Following is a result in the console.

Inheritance

shape Description

Inheritance is a one of the most useful feature in the Object Oriented Programming. Inheritance is used to "Get the properties from the base class to derived class".We can derive one or more classes from its Base class. In VB.Net, we have to use "Inherites" keyword to inherit the base class. There are different types of inheritance are there in Object Oriented Programming.

shape Syntax

See the below syntax to know how to work with the inheritance. [vbnet] Class A End Class Class B : Inherits A End Class [/vbnet]

shape Example

[vbnet] Class A 'Class Definition Public a As Integer = 10 Public b As Integer = 20 Public Function AddResult() As Integer Return a + b End Function End Class Class B : Inherits A Public Function SubResult() As Integer Return a - b End Function End Class Module Module1 Sub Main() Dim obj As B = New B() 'Object declaration Console.WriteLine("Addition of two numbers is") Console.WriteLine(obj.AddResult()) 'Accessing the function in the class using object Console.WriteLine("Substraction of two numbers is") Console.WriteLine(obj.SubResult()) Console.ReadKey() End Sub End Module [/vbnet] Output: Following is a result to an inheritance concept.

Summary

shape Points

  • Re usability is an excellent feature of inheritance.
  • In VB.Net MyBase is nothing but super class.
  • Class name should start with Capital letter.