Friday 6 January 2012

Article1:-Concept of Classes and Constructor with Example


For Asp.net Training with C# Click Here

Written By:-Isha Malhotra
Email:-malhotra.isha3388@gmail.com

Ques:-1 What is the Class?
Ans:- Class is the way to realize real time entity in oops. It is the user defined data type.
Syntax of Class
public class Class_Name
Note: public is an access modifier which can be anything like public,private etc.

Ques:-2 What is the Object?
Ans:-Object is the Runtime Entity of the Class.
Syntax of object Creation
Class_Name  object_Name=new Class_Name()

Ques:3 What is Constructor?
Ans:-Constructor is the method inside the class which is used to initialize or give default value to the class member variable. It is invoked when we create new instance of the class.
Features of Constructor
It has same name as the name of the class
It is called automatically when the instance of the class created.
It doesn’t have any return type not even void
Syntax of Constructor
Public class_name()
{
}

Example of Class,Object and Constructor
In the following example we are creating a class in which declare two variable of type integer and a constructor which initialize these values with some hardcorded value.
AppCode/Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Class1  //Class Creation Syntax
{
    public int x; //variable of class
    public int y;
       public Class1() //construtor(on the name of the class)
       {
        x = 2; //initializing the value
        y = 3;
       }
}

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Class1 cl = new Class1();//object creation
        lblx.Text = cl.x;//calling the variable
        lbly.Text = cl.y;

    }
}
We create the instance of the class1 cl. At the time of creating the class’s object the constructor has called automatically and after that we show these class variable values in the lables which shows the following output.



Output


No comments:

Post a Comment