Pages

Sunday, 14 June 2015

About Classes

About a Class

Before the days of object-oriented analysis and design, programmers thought of a program as just a sequence of instructions. The focus at that time was on structuring and optimizing those instructions.

With the advent of the object-oriented paradigm, the focus changed from optimizing instructions to organizing a program’s data and functions into encapsulated sets of logically related data items and functions, called classes.

A class is a data structure that can store data and execute code. It contains data members and function members:
  • Data members store data associated with the class or an instance of the class. Data members generally model the attributes of the real-world object the class represents.
  • Function members execute code. These generally model the functions and actions of the real-world object the class represents.
A C# class can have any number of data and function members. Following table describes the possible members of a class
Data Members Store Data Function Members Execute Code
Fields Methods Operators
Constants Properties Indexers
Constructors Events
Destructors

Declaring a Class

A class declaration defines the characteristics and members of a new class. It does not create an instance of the class but creates the template from which class instances will be created. The class declaration provides the following:
  • The class name
  • The members of the class
  • The characteristics of the class
The simple way to declaring a class is:
[Access Modifier:Optional] Class [Class Name]
{
  [Class Member]
}

For a simple example, the bank account in real world has an account number, first name, last name and account balance, can do some action like store, withdraw and check balance. We can encapsulate those characteristics:
public class account
{ 
 private uint accoundID;     //field accountID
 private string accountFirstName;  //field accountFirstName
 private string accountLastName;   //field accountLastName
 private decimal accountBalance;   //field accountBalance

 public account(uint ID, string firstName, string LastName) //Class's Constructor
 {
  accoundID = ID;
  accountFirstName = firstName;
  accountLastName = LastName;
 }
 
 public void store(decimal ammount)  //method store
 {
  Console.WriteLine(accountFirstName + " " + accountLastName + " store :" + ammount);
  accountBalance += ammount;
 }

 public void withdraw(decimal ammount) //method withdraw
 {
  Console.WriteLine(accountFirstName + " " + accountLastName + " withdraw :" + ammount);
  accountBalance -= ammount;
 }

 public void checkBalance()    //method checkBalance
 {
  Console.WriteLine(accountFirstName + " " + accountLastName + " has " + accountBalance);
 }
}  

In the example we use public and private access modifier. We'll learn both next.

0 comments:

Post a Comment