4.1.2.3 - Classes, objects and encapsulation (VB.NET)
Learn to define classes, create distinct objects and protect their state through controlled methods. Distinguish instance, shared, virtual and abstract methods in VB.NET. This route is incomplete: runnable support pending; source tasks have no Run. Inheritance and object relationships are developed in the companion lesson for this specification point.
Classes, fields and methods
A class defines the common structure and behaviour of a kind of object. Its fields (attributes) hold state and its methods implement behaviour. An object is a particular instance of that class: two objects follow the same definition but can hold different field values.
Public Class Meter
Private reading As Integer = 0
Public Sub AddUnit()
reading += 1
End Sub
Public Function CurrentReading() As Integer
Return reading
End Function
End Class
Module Program
Sub Main()
Dim first As New Meter()
Dim second As New Meter()
first.AddUnit()
first.AddUnit()
second.AddUnit()
Console.WriteLine(first.CurrentReading())
Console.WriteLine(second.CurrentReading())
End Sub
End Module
The outputs are 2 and 1. reading is an instance field; it is not one total shared by every Meter. first.AddUnit() acts on the object reached through first. An instance method operates in the context of a specific object, and Me refers to that current object within the class.
OOP groups related state and behaviour so a large program can reflect a useful model, such as many independent accounts or meters. It can make common behaviour reusable and changes local to a class. This is a design benefit, not proof that every problem needs objects or that classes automatically prevent errors.
Constructors and references
Instantiation creates an object from its class. A constructor initialises the new object's state. VB.NET uses Sub New; unlike a Function, a constructor does not declare or return a result type. When no constructor is declared for the simple Meter above, a parameterless constructor is supplied implicitly.
Public Class Reading
Private value As Integer
Public Sub New(ByVal initial As Integer)
value = initial
End Sub
Public Sub Increase()
value += 1
End Sub
Public Function ValueNow() As Integer
Return value
End Function
End Class
Module Program
Sub Main()
Dim a As New Reading(6)
Dim b As Reading = a
Dim c As New Reading(6)
b.Increase()
Console.WriteLine(a.ValueNow())
Console.WriteLine(c.ValueNow())
End Sub
End Module
New Reading(6) constructs an object and returns its reference for assignment to a variable of class type. b = a copies the reference: a and b are aliases for one object. It does not call the constructor or clone the object's fields. c reaches another newly constructed object. Increasing through b therefore makes the outputs 7 and 6.
A reference variable can also hold Nothing, meaning no object is referenced. Calling an instance method through Nothing fails; declaring Dim x As Reading alone does not create a Reading. Prefer an explicit New or a deliberately supplied reference before use. Object lifetime is not the same as one variable's scope: another alias may still reach the object after one variable leaves scope.
Encapsulation and access
Encapsulation groups data with its operations and hides implementation details behind a controlled public interface. Private fields plus meaningful methods can preserve an invariant: a rule that must stay true, such as a wallet balance never being negative. Merely adding a public setter that accepts any value would not preserve that rule.
Public Class Wallet
Private balance As Integer
Public Sub New(ByVal initial As Integer)
If initial < 0 Then
Throw New ArgumentOutOfRangeException(NameOf(initial))
End If
balance = initial
End Sub
Public Function TrySpend(ByVal amount As Integer) As Boolean
If amount < 0 OrElse amount > balance Then
Return False
End If
balance -= amount
Return True
End Function
Public Function BalanceNow() As Integer
Return balance
End Function
End Class
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account