Translate

Monday 24 June 2013

Parameterless Constructors

It can be tedious to initialize all of the variables in a class each time an instance is created. Because the requirement for initialization is so common, Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.

A  constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a class constructor is the class type itself. It is the constructor's job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.

Example:

class ConstructorDemo
{
int count;
String strName;

// This is constructor for class
ConstructorDemo()             // Constructor Name=Class name
{
count=10;                            // initializing int type variable
strName="First String";       // initializing string type variable
System.out.println("I am inside the Constructor");    
}
}

class CreateConstructorDemoObject
{
public static void main(String args[])
{
ConstructorDemo obj=new ConstructorDemo();    // This statement calls Constructor
System.out.println("I am outside the Constructor");
}
}

When this program is run, it generates the following results:

I am inside the Constructor
I am outside the Constructor