Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

VB.Net - Classes and objects


May 13, 2021 vb.net


Table of contents


When you define a class, you can define blueprints for data types. This does not actually define any data, but it defines the meaning of the class name, that is, what the object of the class will contain and what can be done with such an object.

An object is an instance of a class. The methods and variables that make up a class are called members of the class.


The definition of the class

The definition of a class begins with the keyword Class, followed by the class name; a nd class bodies, which end with end Class statements. T he following is the general form of a class definition:

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

  • attributelist property list: is a list of attributes that apply to the class. O ptional. al. ptional.

  • accessmodifier access modifier: defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. O ptional. A ccessmodifier defines the access level of the class, which is valued - Public, Protected, Friend, Protected Friend, and Private. Optional.

  • Shadows Shadows: direct that the variable re-declares and hides an identical named, element, or set of overloaded elements, in a base class. O ptional. S hadows represent variables that redo and hide an element with the same name or a set of overloaded elements in the base class. Optional.

  • MustInherit: specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. O ptional. M ustInherit specifies that the class can only be used as a base class and cannot be created directly from it, that is, an abstract class. Optional.

  • NotInheritable is not inheritable: specifyes that class can be used as a base class. NotInheritable specifies that the class cannot be used as a base class.

  • Partial part: levels a partial definition of the class. Partial represents a partial definition of a class.

  • Inherits inheritance: specifies the base class it is inheriting from. Inherits specifies the base class it inherits.

  • Implements implementation: specifyes the interfaces the class is inheriting from. Implements specifies the interface that the class inherits.


The following example demonstrates a Box class that has three data members, length, width, 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 results:

Volume of Box1 : 210
Volume of Box2 : 1560


Member functions and encapsulation

A member function of a class is a function whose definition or its prototype is like any other variable in the class definition. It operates on any object of the class to which it belongs and has access to all members of the object's class.

Member variables are properties of objects (from a design perspective) that are kept private for encapsulation. These variables can only be accessed using the public member function.

Let's set the concept above and get the values of the different class members in the class:

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 results:

Volume of Box1 : 210
Volume of Box2 : 1560


Constructors and destructors

A class constructor is a special member sub-class of a class that is executed whenever we create a new object for that class. The constructor has the name New and does not have any return type.

The following program explains the concept of constructors:

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 results:

Object is being created
Length of line : 6


The default constructor does not have any arguments, but the constructor can have arguments if needed. S uch constructors are called paramethy constructors. T his technique helps you assign an initial value to an object when it is created, as shown in the following example:

Class Line
   Private length As Double    ' Length of a line
   Public Sub New(ByVal len As Double)   'parameterised constructor
      Console.WriteLine("Object is being created, length = {0}", len)
      length = len
   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(10.0)
      Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class


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

Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6


A destructor is a special member of a class, Sub, that is executed as long as the object of its class is out of scope.


The destructor, called Financialize, can neither return a value nor accept any parameters. Destructors are useful for freeing resources before releasing programs, such as closing files, freeing memory, and so on.

Destructors cannot be inherited or overloaded.

The following example explains the concept of destructors:

Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'parameterised constructor
      Console.WriteLine("Object is being created")
   End Sub
   Protected Overrides Sub Finalize()  ' destructor
      Console.WriteLine("Object is being deleted")
   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 results:

Object is being created
Length of line : 6
Object is being deleted


Vb. A shared member of a Net class

We can use the Shared keyword to define class members as static. When we declare a member of a class as a Shared, it means that no matter how many objects are created, the member has only one copy.

The keyword "share" means that the class has only one member instance. Shared variables are used to define constants because their values can be retrieved by calling a class without creating an instance of it.

Shared variables can be initialized outside of member functions or class definitions. You can also initialize shared variables in a class definition.

You can also declare member functions as shares. S uch functions can only access shared variables. Shared functions exist even before objects are created.

The following example demonstrates the use of shared members:

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 results:

Value of variable num: 3


Inherited

One of the most important concepts in object-oriented programming is inheritance. I nheritance allows us to define a class based on another class, which makes it easier to create and maintain applications. This also provides an opportunity to reuse code functionality and quickly implement time.

When you create a class, the programmer can specify that the new class should inherit members of the existing class, rather than writing completely new data members and member functions. This existing class is called the base class, and the new class is called a derived class.


Base and derived classes:

Classes can be derived from multiple classes or interfaces, which means that it can inherit data and functions from multiple base classes or interfaces.

Vb. The syntax used in Net to create derived classes is as follows:

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


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 results:

Total area: 35


Base class initialization

Derived classes inherit base class member variables and member methods. T herefore, you should create a super-class object before you create a sub-class. Supersymsters or base classes VB.Net called MyBase in a class

The following program demonstrates this:

' 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 results:

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

Vb. N et supports multiple inheritances.