SIGN UP MEMBER LOGIN:    
ARTICLE

Introduction to Classes and Objects

Posted by Sivaraman Dhamodaran Articles | C# Language October 22, 2010
A brief introduction to classes and objects.
Reader Level:
Download Files:
 

A class is a blue print or a template. One or more instances of the template is/are known as object(s). 

You can declare a class like below:

A Simple form of Declaration-

public class phone
{
//Some Code here
}

A Class is a combination of member functions (Methods) and member variables (fields). A class can also have properties. And, a property is like member variable but can decide what value to take and what value not to take. Similarly, it can decide how a value can be retrieved.

The real world representation considers methods as the object's behavior and fields as the state of the object. 

Let us consider the below example:

using System;
class Phone
{
    private string model;
    private string make;
    private int cost;
    static void Main(string[] args)
    {
    }
}

The phone class has three states now. These member variables will say model, make and cost of the phone. Static void main is the entry point of the console program execution. To create an object based on the above template that is to create an object of the above class, use the following statement:

Phone myphone = new Phone();

Here, 

myphone - The actual object
Phone - the template
new - Keyword that tells we want to create a real object and allocate space required for it.

To initialize the class fields we can use a special method called constructor. The constructor is called when the object is created. If there is no parameters in the constructor, then we can say it is a default constructor. When translating your class the compiler makes sure to add a default constructor (Parameter less constructor) when it is not available; that is, when it is not implemented by you.

class Phone
{
          //001: Adding fields
          private string model;
          private string make;
          private int cost; 
          //002: Adding a default constructor
            public Phone()
            {
                        model = "823CK";
                        make = "Samsung";
                        cost = 2000;
            }
           static void Main(string[] args)
          {
                   Phone myphone = new Phone();
          }
}

Like function overloading, a constructor can also be overloaded. A constructor can accept parameters, but do not return any value back. Below is the overloaded version of constructor:

//003: Overloaded constructor
public Phone(string model, string make_param, int price)
{
          this.model = model;
          make = make_param;
          cost = price;
}

In the above overloaded constructor note the usage of this.model. The "this" keyword refers the object that is being constructed here. As the parameter variable name model is having the same name of member variable model, this keyword is used to differentiate.

Methods or member functions defines the behavior of the class. It will accept parameters and return value. Let us add some function to the phone class:

//004: Function: Get Discount
float getDiscount(int percent)
{
          if (percent<0)
                   percent = 0;
          if (percent>100)
                   percent = 100;
          return (float) (this.cost * percent / 100);
}
//Function: Display current states
void display()
{
          Console.WriteLine("Make:{0}, Model:{1}, Cost:{2}", make, model, cost );
}

To access the members of the class use the dot (.) operator. Below is the code that uses the class created above:

//005: Create an object using default constructor
Phone myfirstphone = new Phone();

//006: Make a call to the member function to display the state
myfirstphone.display();

//007: Construct another object using overloaded constructor
Phone mySecondPhone = new Phone("70CF", "Samsung", 7000);
Console.WriteLine("I got a Discount of: {0}", mySecondPhone.getDiscount(10));

Login to add your contents and source code to this article
Article Extensions
Contents added by praveen rapelli on Oct 27, 2010
Download File: 001.zip
Contents added by praveen rapelli on Oct 27, 2010
share this article :
post comment
 

Can you show this class diagram? Its nice article. I think its necessary to code from uml diagram whenever we code class? Do you agree? I want to know the developer process when he faced with real world problem? Excellent article!!! Thanks, Nimesh

Posted by Nimesh Patel Apr 08, 2011

Sure. Thanks for your reply.

Posted by Sivaraman Dhamodaran Oct 23, 2010

Hi friend,
Nice work,Can you add some more Oops Conceps.

Thanks


Posted by Satyapriya Nayak Oct 22, 2010
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Team Foundation Server Hosting
Become a Sponsor