In most OO languages, properties are used to define getter and setter functions to change the value of or read and return the value of an attribute in a class. The way properties are defined varies across programming languages.
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
classSavingsAccount{// Variables are made private to prevent illegal accessing out of the objectprivatestringaccountNo;publicstringAccountNo{get{returnaccountNo;}set{accountNo=value;}// Can be extended to have additional checks or validation}privatestringaccountName;publicstringAccountName{get;set;}// Shorthand}
A special function used to create objects of a class. Usually a required method in many OO programming languages.
The following code chunks below show some examples for different languages:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
classSavingsAccount{// The name of the class and constructor must match.// Default constructor — does not have parameterspublicSavingsAccount(){}// Parameterised constructor with parameterspublicSavingsAccount(stringno,stringname,doublebal){AccountNo=no;AccountName=name;Balance=bal;}}
Python
1
2
3
4
5
6
7
8
9
10
11
classSavingsAccount:# The name of the constructor must be __init__.# Default constructor — does not have parametersdef__init__(self):pass# Parameterised constructor with parametersdef__init__(self,no,name,bal):self.accountNo=noself.accountName=nameself.balance=bal
Because we won’t know what exactly to print out, we may need to define what to print out when a language’s printing function is called on an object of a class. The name of the function varies across programming languages.
C#
1
2
3
4
5
6
7
8
9
classSavingsAccount{// The name of the function must be ToString.publicoverridestringToString(){return"AccountNo: "+AccountNo+" AccountName: "+AccountName+" Balance: "+Balance;}}
Python
1
2
3
4
5
6
classSavingsAccount:# The name of the function must be __str__.def__str__(self):return"AccountNo: "+self.accountNo+" AccountName: "+self.accountName+" Balance: "+self.balance