Follow by Email

Friday, March 29, 2013

Constructors

Constructors are the methods in a class. The name of the constructors is same as the class name. Whenever we create object of class, constructor will get called.

Syntax :

class shape
{
  public shape()
  {
      //code
   }
}

shape s = new shape() --> shape constructor will get called here.

Types of constructor :

1. Default constructor:

This type of constructor don't have any parameter in there method.

example : 


class shape
{
  public shape() //--> no parameter
  {
      //code
   }
}


2. Parameterized Constructor:

This type of constructor can have parameters in there method.

example : 


class shape
{
  public shape(int width) //--> parameter constructor
  {
      //code
   }
}

3. Copy constructor :

In this type of constructor a object of a class is copied to the another object of the same class

example:



4. Constructor Overloading

Constructor overloading  include both default and Parameterized constructor. Here the  constructor can be with parameters or without parameters.

when we create object if we pass parameter value while creating the object that constructor  with that number of parameter will get called.

Example:
class shape
{
 public shape()
}

public shape(int x)
}

public shape(int x, int y)
}

}

class main
{
shape s = new shape(10) // this will call the constructor with one parameter.
}

5. Static constructor

this type of constructor gets called before the object creation.

example:

class shape
{
 static shape()
 {

 }
}

Now this method gets executed before the object creation of the class.