Microsoft Docs

Documentation for developers

Object-Oriented Programming (OOP) in VB.NET

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data in the form of fields (often known as attributes or properties) and code in the form of procedures (often known as methods).

Core Concepts of OOP

VB.NET fully supports the core principles of OOP:

Classes and Objects

A class is a blueprint for creating objects. It defines the properties (data) and methods (behaviors) that objects of that class will have. An object is an instance of a class.

Defining a Class


Public Class Car
    ' Properties
    Public Property Make As String
    Public Property Model As String
    Public Property Year As Integer

    ' Constructor
    Public Sub New(make As String, model As String, year As Integer)
        Me.Make = make
        Me.Model = model
        Me.Year = year
    End Sub

    ' Method
    Public Sub DisplayInfo()
        Console.WriteLine($"Car: {Year} {Make} {Model}")
    End Sub
End Class
            

Creating and Using Objects


' Create an instance of the Car class
Dim myCar As New Car("Toyota", "Camry", 2023)

' Access properties
Console.WriteLine($"Make: {myCar.Make}")

' Call a method
myCar.DisplayInfo()
            

Inheritance

Inheritance allows you to create a new class that reuses, extends, and modifies the behavior defined in another class. The class whose properties are inherited is called the base class, and the class that inherits these properties is called the derived class.

Base Class


Public Class Vehicle
    Public Property Color As String
    Public Sub Honk()
        Console.WriteLine("Beep beep!")
    End Sub
End Class
            

Derived Class


Public Class Bicycle
    Inherits Vehicle

    Public Property NumberOfGears As Integer

    Public Sub RingBell()
        Console.WriteLine("Ring ring!")
    End Sub
End Class
            

Using Inheritance


Dim myBike As New Bicycle()
myBike.Color = "Red" ' Inherited property
myBike.NumberOfGears = 10
myBike.Honk()       ' Inherited method
myBike.RingBell()
            

Polymorphism

Polymorphism enables you to treat objects of different classes in a uniform way if they share a common base class or implement a common interface.

Method Overriding

To enable polymorphism, you often use method overriding. The base class method must be marked with Overridable, and the derived class method must be marked with Overrides.


Public Class Shape
    Public Overridable Function GetArea() As Double
        Return 0.0
    End Function
End Class

Public Class Circle
    Inherits Shape

    Public Property Radius As Double

    Public Overrides Function GetArea() As Double
        Return Math.PI * Radius * Radius
    End Function
End Class

Public Class Rectangle
    Inherits Shape

    Public Property Width As Double
    Public Property Height As Double

    Public Overrides Function GetArea() As Double
        Return Width * Height
    End Function
End Class
            

Using Polymorphism


Dim shapes As New List(Of Shape)()
shapes.Add(New Circle() With {.Radius = 5.0})
shapes.Add(New Rectangle() With {.Width = 4.0, .Height = 6.0})

For Each shape As Shape In shapes
    Console.WriteLine($"Area: {shape.GetArea()}") ' Calls the appropriate overridden method
Next
            

Abstraction

Abstraction is achieved through abstract classes and interfaces. Abstract classes cannot be instantiated directly and may contain abstract methods that derived classes must implement. Interfaces define a contract that implementing classes must adhere to.

Abstract Class Example


Public MustInherit Class Document
    Public MustOverride Function Open() As Boolean
    Public Sub Close()
        Console.WriteLine("Document closed.")
    End Sub
End Class

Public Class TextDocument
    Inherits Document

    Public Overrides Function Open() As Boolean
        Console.WriteLine("Text document opened.")
        Return True
    End Function
End Class
            

Tip: Use abstract classes when you want to share common code and enforce a common structure among derived classes. Use interfaces when you want to define a contract without providing any implementation.

Properties vs. Fields

While classes can have fields to store data, it's more common and recommended in VB.NET to use properties. Properties provide a flexible mechanism to read, write, or compute the value of a private field.


Public Class Person
    Private _name As String

    ' Public property with getter and setter
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(value As String)
            If Not String.IsNullOrWhiteSpace(value) Then
                _name = value
            End If
        End Set
    End Property
End Class
            

Important: Encapsulating fields using properties is a cornerstone of OOP, allowing for better control and maintainability of your code.

Understanding and applying these OOP concepts is crucial for building robust, scalable, and maintainable applications in VB.NET.