Constructor Overriding in Visual Basic .NET
In this lesson, I will show you how to do constructor overriding in VB.NET. We have base class named People and we have sub class named Student
Both the classes have constructors Public Sub New()
. Inside the constructor you can see console message
This is the People Class
Public Class People Private strFirstName As String Private strLastName As String Private dtrDateOfBirth As Date Public Sub New() Console.WriteLine("Super Class Constructor") End Sub Public Property FirstName() As String Get Return strFirstName End Get Set(value As String) strFirstName = value End Set End Property Public Property LastName() As String Get Return strLastName End Get Set(value As String) strLastName = value End Set End Property Public Property DateOfBirth() As String Get Return dtrDateOfBirth End Get Set(value As String) dtrDateOfBirth = value End Set End Property End Class
This is the Student Class
Public Class Student Inherits People Private strCourse As String Public Sub New() Console.WriteLine("Sub Class Constructor") End Sub Public Property Course() As String Get Return strCourse End Get Set(value As String) strCourse = value End Set End Property End Class
I have just created object p which is a instance of People and S instance of Student class
Module Module1 Sub Main() Dim p As New People p.FirstName = "John" p.LastName = "Doe" p.DateOfBirth = Date.Parse("11-09-1980") Dim s As New Student Console.ReadLine() End Sub End Module
You can see the console output as below
Super Class Constructor Super Class Constructor Sub Class Constructor
When you create a object from subclass. It first call the base class constructor and then call the sub class constructor
Now I am going to add another constructor with one argument to Sub Class
Public Sub New(ByVal fName As String) Me.FirstName = fName Console.WriteLine("Sub Class Constructor with argument") End Sub
Now I will change the main module as below
Module Module1 Sub Main() Dim p As New People p.FirstName = "John" p.LastName = "Doe" p.DateOfBirth = Date.Parse("11-09-1980") Dim s As New Student("John") Console.ReadLine() End Sub End Module
Changed only the Line 10. It passes the constructor argument when creating the object
Now you get the output
Super Class Constructor Super Class Constructor Sub Class Constructor with argument