What is polymorphism in vb net

Polymorphism and Overloading

Fortunately, we don’t need to go into the details of polymorphism and overloading, which is just as well, because they tend to be both confusing and ambiguous. For instance, some computer scientists say that overloading is a form of polymorphism, whereas others say it is not. We will discuss only those issues that are directly relevant to the .NET Framework.

Overloading

Overloading refers to an item being used in more than one way. Operator names are often overloaded. For instance, the plus sign (+) refers to addition of integers, addition of singles, addition of doubles, and concatenation of strings. Thus, the plus symbol (+) is overloaded. It’s a good thing, too; otherwise, we would need separate symbols for adding integers, singles, and doubles.

Function names can also be overloaded. For instance, the absolute value function, Abs, can take an integer parameter, a single parameter, or a double parameter. Because the name Abs represents several different functions, it is overloaded. In fact, if you look at the documentation for the Abs member of the Math class (in the System namespace of the Framework Class Library), you will find the following declarations, showing the different functions using the Abs name:

Overloads Public Shared Function Abs(Decimal) As Decimal
Overloads Public Shared Function Abs(Double) As Double
Overloads Public Shared Function Abs(Integer) As Short
Overloads Public Shared Function Abs(Integer) As Integer
Overloads Public Shared Function Abs(Long) As Long
Overloads Public Shared Function Abs(SByte) As SByte
Overloads Public Shared Function Abs(Single) As Single

Note the use of the Overloads keyword, which tells VB that this function is overloaded.

Specifically, a function name is overloaded when two defined functions use the same name but have different argument signatures. For instance, consider a function that retrieves a current account balance. The account could be identified either by the person’s name or by the account number. Thus, we might define two functions, each called GetBalance:

Overloads Function GetBalance(sCustName As String) As Decimal
Overloads Function GetBalance(sAccountNumber As Long) As Decimal

Note also that VB.NET permits function overloading only because the argument signatures of the two functions are different, so that no ambiguity can arise. The function calls:

GetBalance("John Smith")
GetBalance(123456)

are resolved by the compiler without difficulty, based on the data type of the argument. This type of overloading is often referred to as overloading the function GetBalance. On the other hand, there are two different functions here, so it seems more appropriate to say that the function name is being overloaded. Overloading is very common and not exclusive to object-oriented programming.

Polymorphism

The term polymorphism means having or passing through many different forms. In the .NET Framework, polymorphism is tied directly to inheritance. Again, let us consider our Employee example. The function IncSalary is defined in three classes: the base class CEmployee and the derived classes CExecutive and CSecretary. Thus, the IncSalary function takes on three forms. This is polymorphism, VB.NET style.

In case you are interested, many computer scientists would not consider this to be polymorphism. They would argue that the function IncSalary takes on only one form. It is the implementation that differs, not the function. They would refer to the situation described here for IncSalary as function overloading. The main point here is that there is a lot of confusion as to how Microsoft and others use the terms overloading and polymorphism, so you should be on guard when reading documentation.

Get VB.NET Language in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Object-oriented programming (Visual Basic)

  • Article
  • 09/15/2021
  • 10 minutes to read

In this article

Visual Basic provides full support for object-oriented programming including encapsulation, inheritance, and polymorphism.

Encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object.

Inheritance describes the ability to create new classes based on an existing class.

Polymorphism means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.

This section describes the following concepts:

  • Classes and objects
    • Class members
      • Properties and fields
      • Methods
      • Constructors
      • Destructors
      • Events
      • Nested classes
    • Access modifiers and access levels
      • Instantiating classes
      • Shared classes and members
      • Anonymous types
  • Inheritance
    • Overriding members
  • Interfaces
  • Generics
  • Delegates

Classes and objects

The terms class and object are sometimes used interchangeably, but in fact, classes describe the type of objects, while objects are usable instances of classes. So, the act of creating an object is called instantiation. Using the blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint.

To define a class:

Class SampleClass
End Class

Visual Basic also provides a light version of classes called structures that are useful when you need to create large array of objects and do not want to consume too much memory for that.

To define a structure:

Structure SampleStructure
End Structure

For more information, see:

  • Class Statement
  • Structure Statement

Class members

Each class can have different class members that include properties that describe class data, methods that define class behavior, and events that provide communication between different classes and objects.

Properties and fields

Fields and properties represent information that an object contains. Fields are like variables because they can be read or set directly.

To define a field:

Class SampleClass
    Public SampleField As String
End Class

Properties have get and set procedures, which provide more control on how values are set or returned.

Visual Basic allows you either to create a private field for storing the property value or use so-called auto-implemented properties that create this field automatically behind the scenes and provide the basic logic for the property procedures.

To define an auto-implemented property:

Class SampleClass
    Public Property SampleProperty as String
End Class

If you need to perform some additional operations for reading and writing the property value, define a field for storing the property value and provide the basic logic for storing and retrieving it:

Class SampleClass
    Private m_Sample As String
    Public Property Sample() As String
        Get
            ' Return the value stored in the field.
            Return m_Sample
        End Get
        Set(ByVal Value As String)
            ' Store the value in the field.
            m_Sample = Value
        End Set
    End Property
End Class

Most properties have methods or procedures to both set and get the property value. However, you can create read-only or write-only properties to restrict them from being modified or read. In Visual Basic you can use ReadOnly and WriteOnly keywords. However, auto-implemented properties cannot be read-only or write-only.

For more information, see:

  • Property Statement
  • Get Statement
  • Set Statement
  • ReadOnly
  • WriteOnly

Methods

A method is an action that an object can perform.

Note

In Visual Basic, there are two ways to create a method: the Sub statement is used if the method does not return a value; the Function statement is used if a method returns a value.

To define a method of a class:

Class SampleClass
    Public Function SampleFunc(ByVal SampleParam As String)
        ' Add code here
    End Function
End Class

A class can have several implementations, or overloads, of the same method that differ in the number of parameters or parameter types.

To overload a method:

Overloads Sub Display(ByVal theChar As Char)
    ' Add code that displays Char data.
End Sub
Overloads Sub Display(ByVal theInteger As Integer)
    ' Add code that displays Integer data.
End Sub

In most cases you declare a method within a class definition. However, Visual Basic also supports extension methods that allow you to add methods to an existing class outside the actual definition of the class.

For more information, see:

  • Function Statement
  • Sub Statement
  • Overloads
  • Extension Methods

Constructors

Constructors are class methods that are executed automatically when an object of a given type is created. Constructors usually initialize the data members of the new object. A constructor can run only once when a class is created. Furthermore, the code in the constructor always runs before any other code in a class. However, you can create multiple constructor overloads in the same way as for any other method.

To define a constructor for a class:

Class SampleClass
    Sub New(ByVal s As String)
        // Add code here.
    End Sub
End Class

For more information, see: Object Lifetime: How Objects Are Created and Destroyed.

Destructors

Destructors are used to destruct instances of classes. In the .NET Framework, the garbage collector automatically manages the allocation and release of memory for the managed objects in your application. However, you may still need destructors to clean up any unmanaged resources that your application creates. There can be only one destructor for a class.

For more information about destructors and garbage collection in the .NET Framework, see Garbage Collection.

Events

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. For more information about events, how they are raised and handled, see Events.

  • To declare events, use the Event Statement.

  • To raise events, use the RaiseEvent Statement.

  • To specify event handlers using a declarative way, use the WithEvents statement and the Handles clause.

  • To be able to dynamically add, remove, and change the event handler associated with an event, use the AddHandler Statement and RemoveHandler Statement together with the AddressOf Operator.

Nested classes

A class defined within another class is called nested. By default, the nested class is private.

Class Container
    Class Nested
    ' Add code here.
    End Class
End Class

To create an instance of the nested class, use the name of the container class followed by the dot and then followed by the name of the nested class:

Dim nestedInstance As Container.Nested = New Container.Nested()

Access modifiers and access levels

All classes and class members can specify what access level they provide to other classes by using access modifiers.

The following access modifiers are available:

Visual Basic ModifierDefinition
Public The type or member can be accessed by any other code in the same assembly or another assembly that references it.
Private The type or member can only be accessed by code in the same class.
Protected The type or member can only be accessed by code in the same class or in a derived class.
Friend The type or member can be accessed by any code in the same assembly, but not from another assembly.
Protected Friend The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

For more information, see Access levels in Visual Basic.

Instantiating classes

To create an object, you need to instantiate a class, or create a class instance.

Dim sampleObject as New SampleClass()

After instantiating a class, you can assign values to the instance's properties and fields and invoke class methods.

' Set a property value.
sampleObject.SampleProperty = "Sample String"
' Call a method.
sampleObject.SampleMethod()

To assign values to properties during the class instantiation process, use object initializers:

Dim sampleObject = New SampleClass With
    {.FirstProperty = "A", .SecondProperty = "B"}

For more information, see:

  • New Operator
  • Object Initializers: Named and Anonymous Types

Shared classes and members

A shared member of the class is a property, procedure, or field that is shared by all instances of a class.

To define a shared member:

Class SampleClass
    Public Shared SampleString As String = "Sample String"
End Class

To access the shared member, use the name of the class without creating an object of this class:

MsgBox(SampleClass.SampleString)

Shared modules in Visual Basic have shared members only and cannot be instantiated. Shared members also cannot access non-shared properties, fields or methods

For more information, see:

  • Shared
  • Module Statement

Anonymous types

Anonymous types enable you to create objects without writing a class definition for the data type. Instead, the compiler generates a class for you. The class has no usable name and contains the properties you specify in declaring the object.

To create an instance of an anonymous type:

' sampleObject is an instance of a simple anonymous type.
Dim sampleObject =
    New With {Key .FirstProperty = "A", .SecondProperty = "B"}

For more information, see: Anonymous Types.

Inheritance

Inheritance enables you to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. However, all classes in Visual Basic implicitly inherit from the Object class that supports .NET class hierarchy and provides low-level services to all classes.

Note

Visual Basic doesn't support multiple inheritance. That is, you can specify only one base class for a derived class.

To inherit from a base class:

Class DerivedClass
    Inherits BaseClass
End Class

By default all classes can be inherited. However, you can specify whether a class must not be used as a base class, or create a class that can be used as a base class only.

To specify that a class cannot be used as a base class:

NotInheritable Class SampleClass
End Class

To specify that a class can be used as a base class only and cannot be instantiated:

MustInherit Class BaseClass
End Class

For more information, see:

  • Inherits Statement
  • NotInheritable
  • MustInherit

Overriding members

By default, a derived class inherits all members from its base class. If you want to change the behavior of the inherited member, you need to override it. That is, you can define a new implementation of the method, property or event in the derived class.

The following modifiers are used to control how properties and methods are overridden:

Visual Basic ModifierDefinition
Overridable Allows a class member to be overridden in a derived class.
Overrides Overrides a virtual (overridable) member defined in the base class.
NotOverridable Prevents a member from being overridden in an inheriting class.
MustOverride Requires that a class member to be overridden in the derived class.
Shadows Hides a member inherited from a base class

Interfaces

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface exactly as it is defined.

To define an interface:

Public Interface ISampleInterface
    Sub DoSomething()
End Interface

To implement an interface in a class:

Class SampleClass
    Implements ISampleInterface
    Sub DoSomething
        ' Method implementation.
    End Sub
End Class

For more information, see:

  • Interfaces
  • Interface Statement
  • Implements Statement

Generics

Classes, structures, interfaces and methods in .NET can include type parameters that define types of objects that they can store or use. The most common example of generics is a collection, where you can specify the type of objects to be stored in a collection.

To define a generic class:

Class SampleGeneric(Of T)
    Public Field As T
End Class

To create an instance of a generic class:

Dim sampleObject As New SampleGeneric(Of String)
sampleObject.Field = "Sample string"

For more information, see:

  • Generics
  • Generic Types in Visual Basic

Delegates

A delegate is a type that defines a method signature, and can provide a reference to any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods.

Note

Event handlers are nothing more than methods that are invoked through delegates. For more information about using delegates in event handling, see Events.

To create a delegate:

Delegate Sub SampleDelegate(ByVal str As String)

To create a reference to a method that matches the signature specified by the delegate:

Class SampleClass
    ' Method that matches the SampleDelegate signature.
    Sub SampleSub(ByVal str As String)
        ' Add code here.
    End Sub
    ' Method that instantiates the delegate.
    Sub SampleDelegateSub()
        Dim sd As SampleDelegate = AddressOf SampleSub
        sd("Sample string")
    End Sub
End Class

For more information, see:

  • Delegates
  • Delegate Statement
  • AddressOf Operator

See also

  • Visual Basic Programming Guide

Feedback

Submit and view feedback for

What is polymorphism in .NET with example?

Polymorphism means one name for many forms. Polymorphism means one object behaving in multiple forms. In other words, "Many forms of a single object is called Polymorphism." One function behaves differently in multiple forms.

What is polymorphism explain briefly?

Polymorphism is a feature of object-oriented programming languages that allows a specific routine to use variables of different types at different times. Polymorphism in programming gives a program the ability to redefine methods for derived classes.

What is polymorphism and types?

Polymorphism is the ability to process objects differently on the basis of their class and data types. As discussed, that polymorphism is of different types, for it to cover different types of data. Nd polymorphism has properties and methods.

What is inheritance and polymorphism in VB net?

Inheritance describes the ability to create new classes based on an existing class. Polymorphism means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.