OOP - Constructors

When we create an instance of the class, we call the default constructor.

ClassName ObjectName = new ClassName();

This is a method that creates the new object. C# creates this method, and we don’t see it.

A constructor is similar to a method, except it shares the same name as the class and is called when a new instance of the class is created.

We can define the constructor ourselves (making an explicit constructor) and put our own code inside.

For example, we could set the initial balance to zero (so that if our main program does not ask for an opening balance this is automatically zero and other methods within the class will still work and not crash the program).

class BankAccount

{

//Define attributes

private string surname;

private str....<code snipped>

//Define Constructors

public BankAccount()

{

this.balance = 0;

}

}

It is possible to have more than one constructor, for use in different situations, however the other versions all need to respond to different arguments.

So far we have created the instances of the class BankAccount, and then set the values of the fields afterwards.

It is possible to pass the values to the instance when it is instantiated by using a constructor.

The syntax for a constructor is as follows:

public class ClassName

{

//define attributes

private int number;

private string text;


//define constructors

//standard constructor

public ClassName()

{

//do this when a new instance is created but no parameters passed

}

//overload constructor

public ClassName(int number, string text)

{

//do this when parameters are sent

//e.g.

this.number = number;

this.text = text;

}


//methods

}

Demo

Create 2 overload constructors.

  • BankAccount(string surname)

  • BankAccount(string surname, string firstName)

Code from Demo

class BankAccount

{

//Define attributes

private string surname; //field

private string firstName;

private double balance;


public string Surname //property

{

get { return surname; } //get method

set { this.surname = value; } //set method

}


public string FirstName //property

{

get { return firstName; } //get method

set { this.firstName = value; } //set methd

}


public double Balance

{

get { return balance; }

}


//Define Constructors

public BankAccount()

{

this.balance = 0;

}


public BankAccount(string surname) //overload constructor

{

this.balance = 0;

this.surname = surname;

}


public BankAccount(string surname, string firstName) //overload constructor

{

this.balance = 0;

this.surname = surname;

this.firstName = firstName;

}



//Define Methods

public string GetSummary()

{

string summary = this.surname + ", " + this.firstName + " - £" + this.balance;

return summary;

}


public bool CreditBalance(double amount)

{

bool validTransaction = false;


if (amount >= 0)

{

validTransaction = true;

this.balance += amount;

}

return validTransaction;

}


}


class MainClass

{

public static void Main(string[] args)

{

string theSurname;

string theFirstName;

double openAmount;


Console.WriteLine("Bank Account Demo 3\n");


//The UI - ask for the surname

Console.Write("Enter surname: ");

theSurname = Console.ReadLine();

Console.Write("Enter first name: ");

theFirstName = Console.ReadLine();


//instantiate an object:

BankAccount myAccount = new BankAccount(theSurname, theFirstName); //call the constructor


Console.Write("Enter the initial deposit: ");

while (!double.TryParse(Console.ReadLine(), out openAmount) || !myAccount.CreditBalance(openAmount))

{

Console.Beep();

Console.WriteLine("Invalid amount");

Console.Write("Enter the initial deposit: ");

}



//Get data from object

Console.WriteLine("The name for this account is {0}, {1}", myAccount.Surname, myAccount.FirstName);

Console.WriteLine("The opening balance is £{0}", myAccount.Balance);

}

}

Challenge

Create a new constructor that has the parameters surname, firstName and balance.

Key Terms

Constructor

The method called which creates the instance. In C# this can be implicit or explicit (where the programmer adds their own code to the method)

Parameter

A variable specified in the definition of a method that allows values to be passed into the method when it is called.

Argument

The value passed into a method call (through a parameter)

Overloading

Creating multiple methods with the same name but different parameters.