pratul
07-02-2010, 12:19 PM
A constructor is a special member function which is automatically invoked whenever the object of the class is created.
1. A constructor has the same name as the class name.
2. There can be more than one constructors in a class.
3. A constructor doesn't have the return type.
4. A constructor can be overloaded.
5.Generally declared in the public section.
6. Constructors are always invoked in the order of their derivation.
Example:
class DemoConstructor
{
private int a;
private int b;
pubic DemoConstructor()
{
a=b=0;
}
pubic DemoConstructor(int a, int b)
{
a=(a>80?80:(a<0?0:a));
b=(b>30?30:(b<0?0:b));
}
public int getA()
{
return a;
}
public int getB()
{
return b;
}
}
class DemoCon {
public static void main(String args[])
{
int w,x,y,z;
DemoConstructor dc1 = new DemoConstructor();
DemoConstructor dc2 = new DemoConstructor(25, 45);
w = dc1.getA()
x = dc1. getB();
y = dc2.getA()
z = dc2. getB();
System,out.println("The value of w is :" +w);
System,out.println("The value of x is :" +x);
System,out.println("The value of y is :" +y);
System,out.println("The value of z is :" +z);
}
}
Explanation: DemoConstructor dc1 = new DemoConstructor();
when this is created then default constructor is invoked that is the constructor which does not take any parameters.
DemoConstructor dc2 = new DemoConstructor(25, 45);
When this is created then the constructor with parameters is invoked and it works accordingly.
1. A constructor has the same name as the class name.
2. There can be more than one constructors in a class.
3. A constructor doesn't have the return type.
4. A constructor can be overloaded.
5.Generally declared in the public section.
6. Constructors are always invoked in the order of their derivation.
Example:
class DemoConstructor
{
private int a;
private int b;
pubic DemoConstructor()
{
a=b=0;
}
pubic DemoConstructor(int a, int b)
{
a=(a>80?80:(a<0?0:a));
b=(b>30?30:(b<0?0:b));
}
public int getA()
{
return a;
}
public int getB()
{
return b;
}
}
class DemoCon {
public static void main(String args[])
{
int w,x,y,z;
DemoConstructor dc1 = new DemoConstructor();
DemoConstructor dc2 = new DemoConstructor(25, 45);
w = dc1.getA()
x = dc1. getB();
y = dc2.getA()
z = dc2. getB();
System,out.println("The value of w is :" +w);
System,out.println("The value of x is :" +x);
System,out.println("The value of y is :" +y);
System,out.println("The value of z is :" +z);
}
}
Explanation: DemoConstructor dc1 = new DemoConstructor();
when this is created then default constructor is invoked that is the constructor which does not take any parameters.
DemoConstructor dc2 = new DemoConstructor(25, 45);
When this is created then the constructor with parameters is invoked and it works accordingly.