Visual Basic .NET Object-Oriented Programming

Explore the core concepts of object-oriented programming in Visual Basic .NET.

Classes and Objects

In object-oriented programming, you model real-world entities as classes. A class is a blueprint for creating objects.

An object is an instance of a class. Each object has its own set of data (properties) and can perform actions (methods) defined in its class.


    Public Class MyClass
        Public Property Name As String
        Public Function Greet() As String
            Return "Hello, " & Name & "!"
        End Function
    End Class

    ' Example usage
    Dim obj As New MyClass()
    obj.Name = "John"
    Console.WriteLine(obj.Greet())
    

Inheritance

Inheritance allows you to create new classes based on existing ones, inheriting their properties and methods. This promotes code reuse and reduces redundancy.


    Public Class Animal
        Public Property Name As String
        Public Function MakeSound() As String
            Return "Generic animal sound"
        End Function
    End Class

    Public Class Dog : Inherits Animal
        Public Sub New(name As String)
            MyBase.Name = name
        End Sub

        Public Override Sub MakeSound() As String
            Return "Woof!"
        End Sub
    End Class

    ' Example usage
    Dim objDog As New Dog("Buddy")
    Console.WriteLine(objDog.MakeSound())
    

Polymorphism

Polymorphism means "many forms". In OOP, it allows objects of different classes to be treated as objects of a common type. This is achieved through interfaces and inheritance.


    Public Interface IShape
        Function Area() As Double
    End Interface

    Public Class Circle
        Public Property Radius As Double
        Function Area() As Double
            Return Math.PI * Math.Square(Radius)
        End Function
    End Class

    Public Class Rectangle
        Public Property Width As Double
        Public Public Property Height As Double
        Public Function Area() As Double
            Return Width * Height
        End Function
    End Class

    ' Polymorphic operation
    Dim shapes() As IObject As Object = New Object() {}
    Dim objCircle As New Circle()
    Dim objRectangle As New Rectangle()

    Array(objCircle, objRectangle)
    
    'Example
    For Each shape As Object In Array(objCircle, objRectangle)
        Console.WriteLine(shape.Area())
    Next