Classes and Objects
17.1 OOP Principles
Encapsulation: hide internal state behind members.
Abstraction: expose only what's essential.
Inheritance: reuse and extend behavior.
Polymorphism: treat different types through a common interface.
17.2 Defining a Class
Public Class BankAccount
' Fields (private state)
Private _balance As Decimal
Private ReadOnly _transactions As New List(Of String)
' Auto-implemented properties
Public Property AccountNumber As String
Public Property Owner As String
' Read-only property
Public ReadOnly Property Balance As Decimal
Get
Return _balance
End Get
End Property
' Constructor
Public Sub New(accountNumber As String, owner As String, Optional initialDeposit As Decimal = 0)
Me.AccountNumber = accountNumber
Me.Owner = owner
If initialDeposit > 0 Then Deposit(initialDeposit)
End Sub
' Methods
Public Sub Deposit(amount As Decimal)
If amount <= 0 Then Throw New ArgumentException("Amount must be positive.")
_balance += amount
_transactions.Add($"Deposit: {amount:C}")
End Sub
Public Function Withdraw(amount As Decimal) As Boolean
If amount > _balance Then Return False
_balance -= amount
_transactions.Add($"Withdraw: {amount:C}")
Return True
End Function
Public Overrides Function ToString() As String
Return $"{AccountNumber}
…17.3 Creating and Using Objects
Dim acc As New BankAccount("ACC-001", "Ana", 500)
acc.Deposit(250)
If Not acc.Withdraw(1000) Then Console.WriteLine("Insufficient funds")
Console.WriteLine(acc) ' calls ToString()
Dim acc2 = New BankAccount("ACC-002", "Bo") With {.Owner = "Bo Smith"} ' object initializer
Dim same = acc ' both variables reference the SAME object
Console.WriteLine(acc Is same) ' True17.4 Me, MyBase, MyClass
The current instance The base class implementation The current class's implementation (ignores overrides in derived classes)
17.5 Object Equality
Is checks reference equality. Equals() checks value equality (override it along with GetHashCode). = works on objects only if the operator is overloaded.
17.6 Nested Types and Anonymous Types
Public Class Outer
Public Class Inner
End Class
End Class
Dim i As New Outer.Inner()
Dim anon = New With {Key .Id = 1, .Name = "Ana"} ' anonymous type; Key fields form equality and hash
Console.WriteLine(anon.Name)