Inheritance
1.1 Definition
Inheritance allows a class (child/derived) to acquire properties and methods of another class (parent/base). It represents an IS-A relationship.
Real-world example: A Car IS-A Vehicle. A Student IS-A Person.
1.2 Syntax in VB.NET
' Parent class
Public Class ParentClass
' fields & methods
End Class
' Child class inherits from ParentClass
Public Class ChildClass
Inherits ParentClass
' additional fields & methods
End Class
Key Point: VB.NET uses the Inherits keyword (unlike Java's extends or C#'s :).
1.3 Types of Inheritance
1.4 Important VB.NET Keywords
1.5 Access Modifiers in Inheritance
1.6 Constructor Behavior
- Parent class constructor executes before child class constructor
- Use
MyBase.New()to explicitly call parent constructor
Polymorphism
2.1 Definition
Polymorphism = "many forms". Same entity behaves differently in different contexts.
2.2 Two Main Types in VB.NET
2.3 Method Overloading Example
Public Class MathUtils
Public Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
Public Function Add(ByVal a As Double, ByVal b As Double) As Double
Return a + b
End Function
Public Function Add(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer) As Integer
Return a + b + c
End Function
End Class
2.4 Method Overriding Example
Public Class Animal
Public Overridable Sub MakeSound()
Console.WriteLine("Animal makes sound")
End Sub
End Class
Public Class Dog
Inherits Animal
Public Overrides Sub MakeSound()
Console.WriteLine("Dog barks")
End Sub
End Class
2.5 Shadows vs Overrides
Lab Activities: VB.NET Programs
Activity 1: Basic Single Inheritance
Problem: Create Employee (id, name, salary) and Manager (bonus). Calculate total pay.
' File: Employee.vb
Public Class Employee
Public Property Id As Integer
Public Property Name As String
Public Property Salary As Double
Public Sub New(ByVal id As Integer, ByVal name As String, ByVal salary As Double)
Me.Id = id
Me.Name = name
Me.Salary = salary
End Sub
Public Overridable Sub Display()
Console.WriteLine($"ID: {Id}, Name: {Name}, Salary: {Salary:C}")
End Sub
End Class
' File: Manager.vb
Public Class Manager
Inherits Employee
Public Property Bonus As Double
Public Sub New(ByVal id As Integer, ByVal name As String, ByVal salary As Double, ByVal bonus As Double)
MyBase.New(id, name, salary) ' Call parent constructor
Me.Bonus = bonus
End Sub
Public Function TotalPay() As Double
Return Salary + Bonus
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine($"Bonus: {Bonus:C}, Total Pay: {TotalPay():C}")
End Sub
End Class
' File: Program.vb
Module Module1
Sub Main()
Dim mgr As New Manager(101, "Ali Ahmed", 50000, 10000)
mgr.Display()
Console.ReadLine()
End Sub
End Module
Expected Output:
ID: 101, Name: Ali Ahmed, Salary: Rs.50,000.00 Bonus: Rs.10,000.00, Total Pay: Rs.60,000.00
Activity 2: Method Overriding with MyBase
Problem: Create BankAccount with CalculateInterest(). Override in SavingsAccount and CurrentAccount.
Public Class BankAccount
Public Property Balance As Double
Public Sub New(ByVal balance As Double)
Me.Balance = balance
End Sub
Public Overridable Function CalculateInterest() As Double
Return Balance * 0.03 ' 3% for normal account
End Function
End Class
Public Class SavingsAccount
Inherits BankAccount
Public Sub New(ByVal balance As Double)
MyBase.New(balance)
End Sub
Public Overrides Function CalculateInterest() As Double
Return Balance * 0.05 ' 5% for savings
End Function
End Class
Public Class CurrentAccount
Inherits BankAccount
Public Sub New(ByVal balance As Double)
MyBase.New(balance)
End Sub
Public Overrides Function CalculateInterest() As Double
Return Balance * 0.01 ' 1% for current
End Function
End Class
' Test Module
Module BankTest
Sub Main()
Dim accounts() As BankAccount = {
New SavingsAccount(10000),
New CurrentAccount(10000)
}
For Each acc As BankAccount In accounts
Console.WriteLine($"{acc.GetType().Name} Interest: {acc.CalculateInterest():C}")
Next
Console.ReadLine()
End Sub
End Module
Expected Output:
SavingsAccount Interest: Rs.500.00 CurrentAccount Interest: Rs.100.00
Activity 3: Polymorphic Array (Abstract Class)
Problem: Create Shape abstract class with Area() method. Extend Circle and Rectangle. Store in array and calculate total area.
' Abstract class
Public MustInherit Class Shape
Public MustOverride Function Area() As Double
End Class
Public Class Circle
Inherits Shape
Public Property Radius As Double
Public Sub New(ByVal radius As Double)
Me.Radius = radius
End Sub
Public Overrides Function Area() As Double
Return Math.PI * Radius * Radius
End Function
End Class
Public Class Rectangle
Inherits Shape
Public Property Length As Double
Public Property Width As Double
Public Sub New(ByVal length As Double, ByVal width As Double)
Me.Length = length
Me.Width = width
End Sub
Public Overrides Function Area() As Double
Return Length * Width
End Function
End Class
' Test Module
Module ShapeTest
Sub Main()
Dim shapes() As Shape = {
New Circle(5),
New Rectangle(4, 6)
}
Dim totalArea As Double = 0
For Each s As Shape In shapes
totalArea += s.Area()
Next
Console.WriteLine($"Total Area of all shapes: {totalArea:F2}")
Console.ReadLine()
End Sub
End Module
Expected Output:
Total Area of all shapes: 102.54
Activity 4: Constructor Chaining
Problem: Show order of constructor execution in inheritance chain.
Public Class A
Public Sub New()
Console.WriteLine("A's constructor called")
End Sub
End Class
Public Class B
Inherits A
Public Sub New()
MyBase.New() ' Optional - called automatically
Console.WriteLine("B's constructor called")
End Sub
End Class
Public Class C
Inherits B
Public Sub New()
' MyBase.New() is automatically called
Console.WriteLine("C's constructor called")
End Sub
End Class
Module ConstructorTest
Sub Main()
Console.WriteLine("Creating object of C:")
Dim obj As New C()
Console.ReadLine()
End Sub
End Module
Expected Output:
Creating object of C: A's constructor called B's constructor called C's constructor called
Activity 5: Shadows Keyword Example
Problem: Demonstrate difference between Overrides and Shadows.
Public Class Parent
Public Overridable Sub Show()
Console.WriteLine("Parent Show method")
End Sub
End Class
Public Class OverrideChild
Inherits Parent
Public Overrides Sub Show()
Console.WriteLine("OverrideChild - Overridden method")
End Sub
End Class
Public Class ShadowChild
Inherits Parent
Public Shadows Sub Show()
Console.WriteLine("ShadowChild - Shadows method")
End Sub
End Class
Module TestShadowVsOverride
Sub Main()
Dim p1 As Parent = New OverrideChild()
Dim p2 As Parent = New ShadowChild()
Console.WriteLine("Using Overrides:")
p1.Show() ' Calls overridden method
Console.WriteLine("Using Shadows:")
p2.Show() ' Calls Parent method (polymorphism broken)
Console.WriteLine("Direct call to ShadowChild:")
Dim s As ShadowChild = New ShadowChild()
s.Show() ' Calls ShadowChild method
Console.ReadLine()
End Sub
End Module
Expected Output:
Using Overrides: OverrideChild - Overridden method Using Shadows: Parent Show method Direct call to ShadowChild: ShadowChild - Shadows method
Activity 6: Interface Implementation (Alternative to Multiple Inheritance)
Problem: Create IPrintable interface and implement in multiple classes.
' Interface
Public Interface IPrintable
Sub PrintDetails()
End Interface
' Base Class
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Sub New(ByVal name As String, ByVal age As Integer)
Me.Name = name
Me.Age = age
End Sub
End Class
' Multiple inheritance simulation using Interface
Public Class Student
Inherits Person
Implements IPrintable
Public Property StudentID As String
Public Sub New(ByVal name As String, ByVal age As Integer, ByVal studentID As String)
MyBase.New(name, age)
Me.StudentID = studentID
End Sub
Public Sub PrintDetails() Implements IPrintable.PrintDetails
Console.WriteLine($"Student: {Name}, Age: {Age}, ID: {StudentID}")
End Sub
End Class
Public Class Teacher
Inherits Person
Implements IPrintable
Public Property EmployeeID As String
Public Sub New(ByVal name As String, ByVal age As Integer, ByVal employeeID As String)
MyBase.New(name, age)
Me.EmployeeID = employeeID
End Sub
Public Sub PrintDetails() Implements IPrintable.PrintDetails
Console.WriteLine($"Teacher: {Name}, Age: {Age}, Employee ID: {EmployeeID}")
End Sub
End Class
Module InterfaceTest
Sub Main()
Dim printableItems As New List(Of IPrintable)
printableItems.Add(New Student("Ahmed", 20, "S123"))
printableItems.Add(New Teacher("Sara", 35, "T456"))
For Each item As IPrintable In printableItems
item.PrintDetails()
Next
Console.ReadLine()
End Sub
End Module
Expected Output:
Student: Ahmed, Age: 20, ID: S123 Teacher: Sara, Age: 35, Employee ID: T456
Assignment / Lab Task (to be submitted)
Problem Statement: Library Management System
Design a system for a Library using VB.NET with the following requirements:
Requirements:
- Base Class
LibraryItemwith properties:
ItemID(Integer)Title(String)Year(Integer)IsAvailable(Boolean)
- Subclass
BookinheritsLibraryItemwith additional properties:
Author(String)Pages(Integer)
- Subclass
DVDinheritsLibraryItemwith additional properties:
Director(String)Duration(Integer) ' in minutes
- Methods:
GetDetails()- Overridable method in base class- Override
GetDetails()in both subclasses BorrowItem()- Marks item as unavailableReturnItem()- Marks item as available
- Polymorphic Method:
- vbnet
Public Sub PrintItemDetails(ByVal item As LibraryItem)
- Main Program:
- Create an array/list of 2 Books and 2 DVDs
- Print all items' details
- Borrow one book and one DVD
- Print details again to show availability change
Expected Output Format:
=== Library Catalog === [Available] Book: 101 - Visual Basic Programming (2021) by John Doe, 450 pages [Available] DVD: 201 - Inception (2010) directed by Nolan, 148 min ... === After Borrowing === [Borrowed] Book: 101 - Visual Basic Programming (2021) by John Doe, 450 pages ...