Lesson 25: Mastering Object-Oriented Programming in VB2022

Learn encapsulation, inheritance, and polymorphism with practical VB.NET examples

Key Takeaway

Object-Oriented Programming (OOP) helps you create modular, reusable code by modeling real-world entities as objects with properties and behaviors.

Welcome to Lesson 25 of our Visual Basic 2022 Tutorial! In this lesson, you'll master the core principles of Object-Oriented Programming in VB2022. While you've been using objects throughout previous lessons, this lesson will give you a comprehensive understanding of how to create and use your own classes effectively.

25.1 The Three Pillars of OOP

Object-Oriented Programming in VB2022 is built on three fundamental principles:

Encapsulation

Bundling data and methods into a single unit (class) while controlling access through access modifiers like Private, Public, and Protected.

Inheritance

Creating new classes based on existing ones, inheriting their properties and methods while adding specialized functionality.

Polymorphism

Allowing objects of different classes to be treated as objects of a common superclass, enabling flexible and reusable code.

Class Relationship Diagram

Class Inheritance Diagram
Figure 25.1: Class inheritance hierarchy showing relationships between base and derived classes

25.2 Creating Classes in VB2022

Classes are defined using the Class keyword. A basic class structure includes:

1 Fields (Data Members)

Variables that store the state of the object

2 Properties

Controlled access to class fields using Get and Set accessors

3 Methods

Functions that define the behavior of the class

4 Constructor

Special method (Sub New) that initializes new objects

Example 25.1: Person Class

This example shows a basic Person class with encapsulation:

Person.vb
Public Class Person
    ' Private fields (encapsulation)
    Private _firstName As String
    Private _lastName As String
    Private _birthDate As Date

    ' Public properties
    Public Property FirstName As String
        Get
            Return _firstName
        End Get
        Set(value As String)
            If Not String.IsNullOrWhiteSpace(value) Then
                _firstName = value
            Else
                Throw New ArgumentException("First name cannot be empty")
            End If
        End Set
    End Property

    Public Property LastName As String
        Get
            Return _lastName
        End Get
        Set(value As String)
            If Not String.IsNullOrWhiteSpace(value) Then
                _lastName = value
            Else
                Throw New ArgumentException("Last name cannot be empty")
            End If
        End Set
    End Property

    Public ReadOnly Property FullName As String
        Get
            Return $"{FirstName} {LastName}"
        End Get
    End Property

    Public Property BirthDate As Date
        Get
            Return _birthDate
        End Get
        Set(value As Date)
            If value <= Date.Today Then
                _birthDate = value
            Else
                Throw New ArgumentException("Birth date cannot be in the future")
            End If
        End Set
    End Property

    Public ReadOnly Property Age As Integer
        Get
            Dim today = Date.Today
            Dim age = today.Year - BirthDate.Year
            If BirthDate.Date > today.AddYears(-age) Then age -= 1
            Return age
        End Get
    End Property

    ' Constructor
    Public Sub New(firstName As String, lastName As String, birthDate As Date)
        Me.FirstName = firstName
        Me.LastName = lastName
        Me.BirthDate = birthDate
    End Sub

    ' Method to display information
    Public Overridable Sub DisplayInfo()
        Console.WriteLine($"Name: {FullName}")
        Console.WriteLine($"Birth Date: {BirthDate.ToShortDateString()}")
        Console.WriteLine($"Age: {Age}")
    End Sub
End Class

Pro Tip: Access Modifiers

Use appropriate access modifiers to control visibility: Public (anywhere), Private (class only), Protected (class and derived classes), Friend (within assembly).

25.3 Implementing Inheritance

Inheritance allows you to create new classes based on existing ones, promoting code reuse.

Keyword Description Usage
Inherits Establishes inheritance relationship Public Class Student Inherits Person
Overridable Allows a method to be overridden in derived classes Public Overridable Sub DisplayInfo()
Overrides Replaces implementation of a base class method Public Overrides Sub DisplayInfo()
MyBase Accesses members of the base class MyBase.DisplayInfo()

Example 25.2: Student Class (Inheritance)

This class extends the Person class with additional properties:

Student.vb
Public Class Student
    Inherits Person

    ' Additional properties specific to Student
    Public Property StudentId As String
    Public Property Major As String
    Public Property GPA As Double

    ' Constructor with base class parameters
    Public Sub New(firstName As String, lastName As String, 
                  birthDate As Date, studentId As String, 
                  major As String, gpa As Double)
        ' Call base class constructor
        MyBase.New(firstName, lastName, birthDate)
        Me.StudentId = studentId
        Me.Major = major
        Me.GPA = gpa
    End Sub

    ' Override DisplayInfo method
    Public Overrides Sub DisplayInfo()
        ' Call base class implementation
        MyBase.DisplayInfo()
        Console.WriteLine($"Student ID: {StudentId}")
        Console.WriteLine($"Major: {Major}")
        Console.WriteLine($"GPA: {GPA.ToString("F2")}")
    End Sub

    ' Additional method specific to Student
    Public Function IsHonorsStudent() As Boolean
        Return GPA >= 3.5
    End Function
End Class

Pro Tip: Inheritance Hierarchy

Design your class hierarchies with care - deep hierarchies can become complex. Favor composition over inheritance when appropriate.

25.4 Understanding Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass.

1 Method Overriding

Derived classes provide specific implementation of base class methods

2 Interfaces

Define contracts that classes implement without specifying how

3 Abstract Classes

Provide partial implementation that derived classes must complete

Example 25.3: Polymorphism with Interfaces

This example demonstrates polymorphism using interfaces:

IPayable.vb
' Define an interface
Public Interface IPayable
    Function CalculatePayment() As Decimal
    Sub ProcessPayment()
End Interface

' Employee class implements IPayable
Public Class Employee
    Inherits Person
    Implements IPayable

    Public Property EmployeeId As String
    Public Property HourlyRate As Decimal
    Public Property HoursWorked As Double

    Public Sub New(firstName As String, lastName As String, 
                  birthDate As Date, employeeId As String, 
                  hourlyRate As Decimal)
        MyBase.New(firstName, lastName, birthDate)
        Me.EmployeeId = employeeId
        Me.HourlyRate = hourlyRate
    End Sub

    ' Implement IPayable interface
    Public Function CalculatePayment() As Decimal Implements IPayable.CalculatePayment
        Return HourlyRate * CDec(HoursWorked)
    End Function

    Public Sub ProcessPayment() Implements IPayable.ProcessPayment
        Dim payment = CalculatePayment()
        Console.WriteLine($"Processing payment of {payment:C} for {FullName}")
        ' Actual payment processing logic would go here
    End Sub
End Class

' Vendor class also implements IPayable
Public Class Vendor
    Implements IPayable

    Public Property VendorName As String
    Public Property InvoiceAmount As Decimal

    Public Sub New(vendorName As String, invoiceAmount As Decimal)
        Me.VendorName = vendorName
        Me.InvoiceAmount = invoiceAmount
    End Sub

    ' Implement IPayable interface
    Public Function CalculatePayment() As Decimal Implements IPayable.CalculatePayment
        Return InvoiceAmount
    End Function

    Public Sub ProcessPayment() Implements IPayable.ProcessPayment
        Console.WriteLine($"Processing vendor payment of {InvoiceAmount:C} to {VendorName}")
    End Sub
End Class

OOP Concepts Summary

Master these essential OOP techniques in VB2022:

Concept Description Key Features
Encapsulation Bundling data and methods Properties, access modifiers, data hiding
Inheritance Creating hierarchical relationships Inherits keyword, base class, derived class
Polymorphism Single interface, multiple implementations Method overriding, interfaces, abstract classes
Abstraction Simplifying complex reality Abstract classes, interfaces

Best Practices

Favor composition over inheritance, program to interfaces, keep classes focused on single responsibility.

Design Principles

Follow SOLID principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion.

Practical Application

Use OOP to create modular, maintainable systems that model real-world entities and relationships.

Practical Exercises

Apply your OOP knowledge with these hands-on exercises:

Exercise 1: Bank Account System

Create a BankAccount base class with properties for account number and balance, and methods for Deposit and Withdraw. Then create SavingsAccount and CheckingAccount classes that inherit from BankAccount with specialized features.

Exercise 2: Shape Hierarchy

Create an abstract Shape class with abstract methods for CalculateArea and CalculatePerimeter. Implement derived classes for Circle, Rectangle, and Triangle.

Exercise 3: Employee Management

Create an interface IEmployee with methods for CalculateSalary and GenerateReport. Implement this interface in FullTimeEmployee and PartTimeEmployee classes with different salary calculation logic.

Exercise 4: Library System

Design a class hierarchy for a library system with LibraryItem base class and derived classes like Book, DVD, and Magazine. Implement polymorphic CheckOut and Return methods.

Exercise 5: Vehicle Rental

Create a Vehicle base class and derived classes Car, Truck, and Motorcycle. Implement an interface IRentable with methods for calculating rental costs.

Next Lesson

Learn how to create graphical applications in Lesson 26: Introduction to Graphics.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More