Objects and Classes in Visual Basic .NET

Understanding the fundamental concepts of object-oriented programming (OOP) is crucial for developing robust and scalable applications in Visual Basic .NET.

What are Objects and Classes?

In Visual Basic .NET, an object is a self-contained unit that encapsulates data (properties) and behavior (methods). Think of it as an instance of a real-world entity. A class, on the other hand, is a blueprint or a template that defines the structure and behavior of objects of a particular type.

You can create multiple objects from a single class, and each object will have its own set of properties, but they will share the same methods defined by the class.

Defining a Class

You define a class using the Class keyword in Visual Basic .NET. A class typically contains:

Example: A Simple `Car` Class


Public Class Car
    ' Fields
    Private _make As String
    Private _model As String
    Private _year As Integer
    Private _isEngineRunning As Boolean = False

    ' Properties
    Public Property Make() As String
        Get
            Return _make
        End Get
        Set(value As String)
            _make = value
        End Set
    End Property

    Public Property Model() As String
        Get
            Return _model
        End Get
        Set(value As String)
            _model = value
        End Set
    End Property

    Public Property Year() As Integer
        Get
            Return _year
        End Get
        Set(value As Integer)
            If value > 1886 Then ' Basic validation
                _year = value
            Else
                Throw New ArgumentOutOfRangeException("Year", "Year must be after 1886.")
            End If
        End Set
    End Property

    ' Constructor
    Public Sub New(make As String, model As String, year As Integer)
        _make = make
        _model = model
        _year = year
        Console.WriteLine($"A new {year} {make} {model} has been created.")
    End Sub

    ' Methods
    Public Sub StartEngine()
        If Not _isEngineRunning Then
            _isEngineRunning = True
            Console.WriteLine($"The {Make} {Model}'s engine is now running.")
        Else
            Console.WriteLine($"The {Make} {Model}'s engine is already running.")
        End If
    End Sub

    Public Sub StopEngine()
        If _isEngineRunning Then
            _isEngineRunning = False
            Console.WriteLine($"The {Make} {Model}'s engine has been stopped.")
        Else
            Console.WriteLine($"The {Make} {Model}'s engine is already stopped.")
        End If
    End Sub

    Public Sub DisplayInfo()
        Console.WriteLine($"Car: {_year} {_make} {_model}")
        If _isEngineRunning Then
            Console.WriteLine("Engine Status: Running")
        Else
            Console.WriteLine("Engine Status: Stopped")
        End If
    End Sub
End Class
            

Creating Objects (Instantiating Classes)

To create an object from a class, you use the New keyword. This process is called instantiation.


' In another part of your code (e.g., a Form's Load event or a Module)

' Create a new Car object
Dim myCar As New Car("Toyota", "Camry", 2022)

' Access properties
Console.WriteLine($"My car is a {myCar.Make} {myCar.Model} from {myCar.Year}.")

' Call methods
myCar.StartEngine()
myCar.DisplayInfo()
myCar.StopEngine()
myCar.DisplayInfo()

' Attempting to create a car with an invalid year
Try
    Dim invalidCar As New Car("Ford", "Model T", 1800)
Catch ex As ArgumentOutOfRangeException
    Console.WriteLine($"Error: {ex.Message}")
End Try
            

Key OOP Concepts Related to Objects and Classes:

  • Encapsulation: Bundling data (properties) and methods that operate on that data within a single unit (class).
  • Abstraction: Hiding complex implementation details and exposing only essential features to the user.
  • Inheritance: Creating new classes (derived classes) that inherit properties and methods from existing classes (base classes).
  • Polymorphism: The ability of objects of different classes to respond to the same method call in their own way.

Access Modifiers

Access modifiers control the visibility and accessibility of class members. Common modifiers include:

Using appropriate access modifiers is crucial for maintaining encapsulation and security in your code.

Further Reading

This section provides a foundational understanding. Explore related topics like Inheritance, Interfaces, and Generics to deepen your knowledge of object-oriented programming in Visual Basic .NET.