Constructors are special methods that are automatically called when creating Objects. We know that we have to initialize objects before using them. There are two ways to initialize members of a class (objects) using constructors.
1.By passing arguments to a constructor, we can initialize member variables as shown below.
Public Class Account
Private mCode As String 'Account code
Private mName As String 'Account Name
Private mdescription As String 'Account description
Protected mBalance As Double 'Account Balance
The below code is an example of an overloaded constructor with arguments.
Public Sub New(ByVal code, ByVal name, ByVal description, ByVal balance)
mCode = code
mName = name
mdescription = description
mBalance = balance
The below code is an example of an overloaded constructor without arguments.
Public Sub New()
2. We can also initialize member variables with default values inside the constructor as shown below.
mName = "Account1"
mdescription ="Default Account"
mBalance = 0.0
mName = "Account1";
mdescription ="Default Account" ;
mBalance = 0.0;
How to initialize Base class Object from inside Derived Class constructor
To access members of the base class, firstly we have to run the base class constructors in the derived class' constructor. This ensures that all the objects are in an initialized state. When we need to access the functionality of a class which is in a inheritance hierarchy, the constructors are executed beginning with the highest base class to the lowest class. In vb.net , the 'MyBase' keyword is used to access any of the base class members.
In the code given below, we use MyBase keyword to call the constructor of the base class - 'Account' class.
Creating a constructor in derived class without parameters is shown below.
Public Sub New()
Creating a constructor in derived class with parameters is shown below.
Public Sub New(ByVal code, ByVal name, ByVal description, ByVal balance, ByVal address, ByVal phone)
MyBase.New(code, name, description, balance)
mAddress = address
mPhone = phone