Classes and Objects in VB.net – What is Class and Object in VB.net

Classes and Objects in VB.net?

The Classes and Objects in VB.net are interrelated. Each Object in VB.net is defined by a Class.

A Class in VB.net describes the variables, properties, procedures, and events of an object.

Objects are instances of classes; you can create as many objects as you need once you have defined a class.

To understand the relationship between an object and its class, think of cookie cutters and cookies.

The cookie cutter is the class. It defines the characteristics of each cookie, for example, size and shape.

The class is used to create objects. The objects are the cookies.

Difference Between Class and Object in VB.net

Class and Object in VB.net
Class and Object in VB.net

Here is an example that will help you to clarify the above points. Suppose we have a class called “CAR“.

All CAR have bodies, engines etc. and these could be the attributes (properties) of our CAR class.

We can also add some methods (functions) that would be common to all CAR like movement (forward and reverse), because all CAR can move.

So, the idea you really want to enforce in your own mind is that the ‘template’ of a CAR does not change.

Each Object was built from the same set of templates (Class) and therefore contains the same components.

All Objects share the same copy of the member functions (methods), but maintain a separate copy of the member data (Properties).

For example: A Ferrari Car and an Audi Car are both Cars, so they can be classified as belonging to the Car class.

All have the same movement (methods) but different models (properties).

What is Class in VB.net?

A Class in VB.net is a collection of various data members or objects that share similar attributes, behaviors, and relationships to other member functions.

Additionally, it can be compared to a template or architect that specifies what data and functions will be included in a class object.

For instance, it represents the variable and method that will operate on the class object.

Here’s the syntax for the Class in VB.net:

'syntax of the class'

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
   [ Inherits classname ]
   [ Implements interfacenames ]
   [ statements ]
End Class

Syntax Explanations:

1. attributelist

The class’s attributes are listed in the document called attributelist.

2. accessmodifier

AccessModifier, which has the values Public, Protected, Friend, Protected Friend, and Private, defines the access levels of the class.

3. Shadows

Shadows show that a variable re-declares and conceals a collection of overloaded elements with the same name in a base class.

4. MustInherit

MustInherit makes it clear that the class, which is an abstract class, can only be used as a base class and cannot be used to directly construct objects.

5. NotInheritable

The class’s NotInheritable attribute indicates that it cannot be used as a base class.

6. Partial

Partial denotes that the class has only been partially defined.

7. Inherits

Inherits specifies the base class it is inheriting from.

8. Implements

The interfaces from which the class derives are specified in implements.

How to use Classes in VB.net?

A class is used in object-oriented programming to describe one or more objects. It serves as a template for creating, or instantiating, specific objects within a program.

Example Program of Class in VB.net:

The following example demonstrates a Box class, with three data members, length, breadth, and height.

Module mybox
   Class Box
      Public length As Double   ' Length of a box
      Public breadth As Double  ' Breadth of a box
      Public height As Double   ' Height of a box
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box
      Dim volume As Double = 0.0         ' Store the volume of a box here
      
      ' box 1 specification
      Box1.height = 5.0
      Box1.length = 6.0
      Box1.breadth = 7.0
      
      ' box 2 specification
      Box2.height = 10.0
      Box2.length = 12.0	
      Box2.breadth = 13.0
      
      'volume of box 1
      volume = Box1.height * Box1.length * Box1.breadth
      Console.WriteLine("Volume of Box1 : {0}", volume)
      
      'volume of box 2
      volume = Box2.height * Box2.length * Box2.breadth
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210
Volume of Box2 : 1560

You can test the above example here! ➡ VB.net Online Compiler

Member Functions and Encapsulation in VB.net

A member function of a class is a function that, like any other variable, has its definition or prototype within the class declaration.

It has access to every member of a class for that object and can operate on any object of that class.

From a design standpoint, member variables are characteristics of an object that are kept secret to implement encapsulation.

The only way to access these variables is through the public member functions.

Example Program of Member Functions and Encapsulation in VB.net:

Module mybox
   Class Box
      Public length As Double    ' Length of a box
      Public breadth As Double   ' Breadth of a box
      Public height As Double    ' Height of a box
      Public Sub setLength(ByVal len As Double)
         length = len
      End Sub
      
      Public Sub setBreadth(ByVal bre As Double)
         breadth = bre
      End Sub
      
      Public Sub setHeight(ByVal hei As Double)
         height = hei
      End Sub
      
      Public Function getVolume() As Double
         Return length * breadth * height
      End Function
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box
      Dim volume As Double = 0.0         ' Store the volume of a box here

      ' box 1 specification
      Box1.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)
      
      'box 2 specification
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)
      
      ' volume of box 1
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210
Volume of Box2 : 1560

You can test the above example here! ➡ VB.net Online Compiler

Constructors and Destructors in VB.net

Every time we create new objects of a class, the class constructor, a specific member Sub of that class, is called.

New is the name of a constructor, and it has no return type.

Example Program of Constructors and Destructors in VB.net:

Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'constructor
      Console.WriteLine("Object is being created")
   End Sub
   
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
     
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line()
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

When the above code is compiled and executed, it produces the following result:

Object is being created
Length of line : 6

You can test the above example here! ➡ VB.net Online Compiler

Shared Members of a VB.net Class

Using the Shared keyword, we can declare a class’s members as static.

When a class member is marked as shared, it indicates that there will only ever be one instance of the member, regardless of how many class objects are produced.

One instance of the member exists for a class, as suggested by the keyword Shared.

Constants are defined as shared variables because doing so allows one to access their values without having to create an instance of the class.

It is possible to initialize shared variables outside of a member function or class definition. Shared variables may also be initialized within the class definition.

A member function may alternatively be designated as Shared.

Only Shared variables may be accessed by such functions. Even before the object is formed, the shared functions already exist.

Example Program of Shared Members of a VB.net Class:

Class StaticVar
   Public Shared num As Integer
   Public Sub count()
      num = num + 1
   End Sub
   Public Shared Function getNum() As Integer
      Return num
   End Function
   Shared Sub Main()
      Dim s As StaticVar = New StaticVar()
      s.count()
      s.count()
      s.count()
      Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
      Console.ReadKey()
   End Sub
End Class

When the above code is compiled and executed, it produces the following result:

Value of variable num: 3

You can test the above example here! ➡ VB.net Online Compiler

Inheritance

In object-oriented programming, inheritance is among the most crucial ideas.

It is simpler to design and manage applications when we can declare a class in terms of another class thanks to inheritance.

Additionally, it allows for quick implementation times and code functionality reuse.

Programmers have the option to specify that a new class should inherit the members of an existing class rather than writing entirely new data members and member functions.

The new class is referred to as the derived class, and the current class is known as the base class.

Base & Derived Classes in VB.net

A class may derive from numerous base classes or interfaces, which allows it to inherit information and features from many base classes or interfaces.

Here’s the syntax for the Base & Derived Classes in VB.net:

<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class

Example Program of Base & Derived Classes in VB.net:

Consider a base class Shape and its derived class Rectangle

' Base class
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(5)
      rect.setHeight(7)
      ' Print the area of the object.
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub	
End Class

When the above code is compiled and executed, it produces the following result:

Total area: 35

You can test the above example here! ➡ VB.net Online Compiler

Base Class Initialization in VB.net

The member variables and member methods of the base class are inherited by the derived class.

As a result, creating the super class object should come before creating the subclass. In VB.net, the base class or super class is implicitly referred to as MyBase.

Example Program of Base Class Initialization in VB.net:

' Base class
Class Rectangle
   Protected width As Double
   Protected length As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      length = l
      width = w
   End Sub
   Public Function GetArea() As Double
      Return (width * length)
   End Function
   Public Overridable Sub Display()
      Console.WriteLine("Length: {0}", length)
      Console.WriteLine("Width: {0}", width)
      Console.WriteLine("Area: {0}", GetArea())
   End Sub
   'end class Rectangle  
End Class

'Derived class
Class Tabletop : Inherits Rectangle
   Private cost As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      MyBase.New(l, w)
   End Sub
   Public Function GetCost() As Double
      Dim cost As Double
      cost = GetArea() * 70
      Return cost
   End Function
   Public Overrides Sub Display()
      MyBase.Display()
      Console.WriteLine("Cost: {0}", GetCost())
   End Sub
    'end class Tabletop
End Class
Class RectangleTester
   Shared Sub Main()
      Dim t As Tabletop = New Tabletop(4.5, 7.5)
      t.Display()
      Console.ReadKey()
   End Sub
End Class

When the above code is compiled and executed, it produces the following result:

Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

You can test the above example here! ➡ VB.net Online Compiler

Summary

Many programmers still get confused by the difference between Class and Object in VB.net. In object-oriented terminology, a Class is a template for Objects and every Object must belong to a Class.

The terms “Class” and “Object” are related to one another and each term holds its own distinct meaning.


Leave a Comment