Object-Oriented Programming (OOP) is a programming style that uses objects to structure code. These objects contain data (properties) and actions (methods).
Hiding details and bundling data with the methods that work on that data.
Allows one class to use the properties and methods of another class.
Methods can behave differently depending on the object that calls them.
Shows only important features while hiding unnecessary details.
// Creating a class
class Animal {
constructor(name) {
this.name = name; // property
}
speak() { // method
console.log(this.name + " makes a sound.");
}
}
// Creating an object from the class
const dog = new Animal("Buddy");
dog.speak(); // Output: Buddy makes a sound.
You can run the JavaScript example below:
' Creating a class
Public Class Animal
Public Property Name As String
Public Sub New(name As String)
Me.Name = name
End Sub
Public Overridable Sub Speak()
Console.WriteLine(Name & " makes a sound.")
End Sub
End Class
' Inheritance example
Public Class Dog
Inherits Animal
Public Sub New(name As String)
MyBase.New(name)
End Sub
Public Overrides Sub Speak()
Console.WriteLine(Name & " barks.")
End Sub
End Class
' Using the classes
Dim pet As New Dog("Buddy")
pet.Speak() ' Output: Buddy barks.
VB.NET cannot run directly in a webpage, but this button simulates the expected output:
Public Class BankAccount
Private balance As Decimal
Public Sub Deposit(amount As Decimal)
If amount > 0 Then
balance += amount
End If
End Sub
Public Function GetBalance() As Decimal
Return balance
End Function
End Class
Dim acct As New BankAccount()
acct.Deposit(100)
Console.WriteLine(acct.GetBalance()) ' Output: 100
Public Class Shape
Public Overridable Function Area() As Double
Return 0
End Function
End Class
Public Class Circle
Inherits Shape
Public Property Radius As Double
Public Sub New(r As Double)
Radius = r
End Sub
Public Overrides Function Area() As Double
Return Math.PI * Radius * Radius
End Function
End Class
Dim c As New Circle(5)
Console.WriteLine(c.Area()) ' Output: 78.5398...
Public Interface IVehicle
Sub Drive()
End Interface
Public Class Car
Implements IVehicle
Public Sub Drive() Implements IVehicle.Drive
Console.WriteLine("The car is driving.")
End Sub
End Class
Dim v As IVehicle = New Car()
v.Drive() ' Output: The car is driving.
Public MustInherit Class Employee
Public Property Name As String
Public MustOverride Function Pay() As Decimal
End Class
Public Class HourlyEmployee
Inherits Employee
Public Property Hours As Integer
Public Property Rate As Decimal
Public Overrides Function Pay() As Decimal
Return Hours * Rate
End Function
End Class
Dim worker As New HourlyEmployee() With {.Name="Sam", .Hours=40, .Rate=20}
Console.WriteLine(worker.Pay()) ' Output: 800
OOP is a powerful way to organize and manage code. Mastering it will help you write cleaner, more effective programs.
PeatSoft - VB.NET - Educational Reference - AI