OOP - Defining a Class
A class is the specification of an Object. Class is short for Classification.
A class is defined by stating the attributes and the methods.
Defining a class is similar to defining a Struct:
class ClassName
{
//define attributes
//define constructors
//define methods
}
To instantiate an object based on the class (create an instance of the class) we declare it as follows:
ClassName ObjectName = new ClassName();
Demo Creating a Class
Code from Demo
class BankAccount
{
//Define attributes
private string surname; //field
private double balance;
public string Surname //property
{
get { return surname; } //get method
set { this.surname = value; } //set method
}
//Define Constructors
//Define Methods
public string GetSummary()
{
string summary = this.surname + ", £" + this.balance;
return summary;
}
}
class MainClass
{
public static void Main(string[] args)
{
string theSurname;
//instantiate an object:
BankAccount myAccount = new BankAccount(); //call the constructor
Console.WriteLine("Bank Account Demo 1\n");
//The UI - ask for the surname
Console.Write("Enter surname: ");
theSurname = Console.ReadLine();
//Assign data to object
myAccount.Surname = theSurname;
//Get data from object
Console.WriteLine("Account Details: {0}", myAccount.GetSummary());
}
}
A key design principle in OOP is the Separation of Concerns.
In our example it is the job of the Main program to interface with the user. This allows our code to be portable. We can use the same BankAccount class in a form app or a console app.
Challenge
Extend the demonstration task by adding:
A new first name field.
Methods to get and set the field
New code to the Main to capture the data and display it.
Key Terms
Instantiation
Creating an instance of an object based on a template (class)
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)