Classes and Objects
In Visual Basic .NET, classes and objects are fundamental concepts in object-oriented programming (OOP). They allow you to model real-world entities and create reusable, modular code.
What are Classes?
A class is a blueprint or a template for creating objects. It defines the properties (data) and methods (behavior) that objects of that class will possess. Think of it like the blueprint for a house – it specifies how many rooms it will have, where the doors and windows will be, and what functions they perform, but it's not the house itself.
What are Objects?
An object is an instance of a class. When you create an object from a class, you are creating a concrete entity based on that blueprint. Each object has its own set of data (values for its properties) but shares the methods defined by its class.
Analogy: A Cookie Cutter and Cookies
Imagine a cookie cutter is a class. It defines the shape of the cookie.
Each cookie you make using that cookie cutter is an object. Each cookie is a separate entity, but they all share the same shape defined by the cookie cutter.
Defining a Class in VB.NET
You define a class using the Class
and End Class
keywords. Inside the class, you declare properties using Property
statements and methods using Sub
or Function
statements.
Example: A Simple `Car` Class
Public Class Car
' Properties
Public Property Make As String
Public Property Model As String
Public Property Year As Integer
Public Property IsEngineRunning As Boolean = False
' Constructor (optional, runs when an object is created)
Public Sub New(make As String, model As String, year As Integer)
Me.Make = make
Me.Model = model
Me.Year = year
Console.WriteLine($"A new {Me.Year} {Me.Make} {Me.Model} has been created.")
End Sub
' Methods
Public Sub StartEngine()
If Not IsEngineRunning Then
IsEngineRunning = True
Console.WriteLine($"{Me.Make} {Me.Model}'s engine started.")
Else
Console.WriteLine($"{Me.Make} {Me.Model}'s engine is already running.")
End If
End Sub
Public Sub StopEngine()
If IsEngineRunning Then
IsEngineRunning = False
Console.WriteLine($"{Me.Make} {Me.Model}'s engine stopped.")
Else
Console.WriteLine($"{Me.Make} {Me.Model}'s engine is already stopped.")
End If
End Sub
Public Sub DisplayCarInfo()
Console.WriteLine($"Car Info: {Me.Year} {Me.Make} {Me.Model}")
Console.WriteLine($"Engine Status: {(If(IsEngineRunning, "Running", "Stopped"))}")
End Sub
End Class
Creating and Using Objects
To create an object (an instance of a class), you use the New
keyword. You can then access the object's properties and call its methods.
Example: Instantiating and Using the `Car` Object
' In another part of your code, e.g., in a Form's Load event or a Sub Main()
Module Module1
Sub Main()
' Create an instance (object) of the Car class
Dim myCar As New Car("Toyota", "Camry", 2023)
' Accessing properties
Console.WriteLine($"My car is a {myCar.Year} {myCar.Make} {myCar.Model}.")
' Calling methods
myCar.StartEngine()
myCar.DisplayCarInfo()
myCar.StopEngine()
myCar.DisplayCarInfo()
' Create another instance of the Car class
Dim anotherCar As New Car("Honda", "Civic", 2022)
anotherCar.StartEngine()
anotherCar.DisplayCarInfo()
Console.ReadLine() ' Keep console window open
End Sub
End Module
Key Concepts:
- Fields: Variables within a class that store data. (e.g.,
Make
,Model
,Year
in the `Car` class) - Properties: Public members that provide controlled access to a class's fields. They typically have a
Get
and aSet
accessor. (e.g.,Public Property Make As String
) - Methods: Functions or Subroutines within a class that define its behavior. (e.g.,
StartEngine()
,StopEngine()
) - Constructor: A special method (named
New
) that is automatically called when an object is created. It's used to initialize the object's state. Me
Keyword: Refers to the current instance of the class within the class itself.
Benefits of Using Classes and Objects:
- Modularity: Code is organized into logical units (classes), making it easier to understand and manage.
- Reusability: Once a class is defined, you can create multiple objects from it, reusing the code.
- Maintainability: Changes to a class can be made in one place, affecting all objects created from it.
- Abstraction: Hides complex implementation details from the user of the class.