Classes in VB.NET
Classes are the fundamental building blocks of object-oriented programming (OOP) in VB.NET. They serve as blueprints for creating objects, encapsulating data (fields or members) and behavior (methods or procedures) that operate on that data.
What is a Class?
A class defines the structure and behavior for a type of object. When you create an object from a class, it's called an instance of that class. Each instance has its own copy of the data defined by the class.
Declaring a Class
You declare a class using the Class keyword. The basic syntax is as follows:
Syntax Example
Public Class ClassName
' Member variables (fields)
Private memberVariable As DataType
' Constructor (optional)
Public Sub New(parameters As DataType)
' Initialize member variables
memberVariable = parameters
End Sub
' Methods (procedures)
Public Sub MethodName(parameters As DataType)
' Code to execute
End Sub
' Properties
Public Property MyProperty As DataType
Get
Return memberVariable
End Get
Set(value As DataType)
memberVariable = value
End Set
End Property
End Class
Class Members
Classes can contain various members:
- Fields (Member Variables): These store the data associated with an object. They are typically declared with access modifiers like
Private,Protected, orPublic. - Methods (Procedures): These define the actions an object can perform. They are subroutines or functions that operate on the object's data.
- Properties: These provide a flexible mechanism for reading, writing, or computing the values of private fields. They use
GetandSetblocks. - Constructors: Special methods named
Newthat are automatically called when an object is created. They are used to initialize the object's state. - Events: Mechanisms for objects to notify other objects when something significant happens.
- Nested Classes: Classes defined within another class.
Access Modifiers
Access modifiers control the visibility and accessibility of class members:
Public: Accessible from anywhere.Private: Accessible only within the class itself.Protected: Accessible within the class and by derived classes.Friend: Accessible within the same assembly.Protected Friend: Accessible within the same assembly or by derived classes.
Creating Objects (Instantiating a Class)
To create an object from a class, you use the New keyword:
Object Instantiation
' Assuming 'MyClass' is a class defined elsewhere
Dim myObject As New MyClass()
' If the constructor takes arguments
Dim anotherObject As New MyClass("initial value")
Accessing Members
You use the dot (.) operator to access the members (fields, methods, properties) of an object:
Accessing Members Example
' Assuming myObject has a public property named 'Name' and a public method 'Greet'
myObject.Name = "Alice"
myObject.Greet()
Example: A Simple `Car` Class
Car Class Definition
Public Class Car
' Fields
Private _make As String
Private _model As String
Private _year As Integer
Private _isRunning As Boolean = False
' Constructor
Public Sub New(make As String, model As String, year As Integer)
_make = make
_model = model
_year = year
End Sub
' Properties
Public Property Make As String
Get
Return _make
End Get
Set(value As String)
_make = value
End Set
End Property
Public ReadOnly Property Model As String ' Read-only property
Get
Return _model
End Get
End Property
Public Property Year As Integer
Get
Return _year
End Get
Set(value As Integer)
If value >= 1886 AndAlso value <= DateTime.Now.Year + 1 Then ' Basic validation
_year = value
Else
Throw New ArgumentOutOfRangeException("Year", "Invalid year provided.")
End If
End Set
End Property
' Methods
Public Sub StartEngine()
If Not _isRunning Then
_isRunning = True
Console.WriteLine("The car's engine has started.")
Else
Console.WriteLine("The car's engine is already running.")
End If
End Sub
Public Sub StopEngine()
If _isRunning Then
_isRunning = False
Console.WriteLine("The car's engine has stopped.")
Else
Console.WriteLine("The car's engine is already stopped.")
End If
End Sub
Public Sub DisplayInfo()
Console.WriteLine($"Car: {_year} {_make} {_model}. Engine running: {_isRunning}")
End Sub
End Class
Using the Car Class
' Create instances of the Car class
Dim myCar As New Car("Toyota", "Camry", 2022)
Dim anotherCar As Car = New Car("Honda", "Civic", 2023)
' Access and modify properties
myCar.Year = 2023
' anotherCar.Model = "Accord" ' This would cause a compile error as Model is ReadOnly
' Call methods
myCar.StartEngine()
myCar.DisplayInfo()
anotherCar.StartEngine()
anotherCar.StopEngine()
anotherCar.DisplayInfo()
' Accessing read-only property
Console.WriteLine($"The model of the first car is: {myCar.Model}")