Pages

Saturday, February 2, 2013

Constructors in Java


What is a Constructor and Applications ?
A special method in Java which is used to initialize the newly created objects. A constructor is called immediately after the memory is allotted to the object. 
Constructors are methods with same name as a class name and do not have a return type. If constructors have a return type then they are no different than general methods, hence they don't have a return type like "void", "int" etc.
A Constructor may or may not have parameters. Constructors with same name and differenet parameters in the same class are said to be overloaded.  Constructor overriding is not possible. Constructor overloading contains two methods with the same name but different signature(parameters)
If no constructor is defined then java creates a default constructor. Constructor cannot be called using an object. Constructors are called only when an object is created. 
Uses :
Constructors are used to initialize the instance variables or to perform operations during object creation.
If there is no user defined constructor in a program, then compiler or the JVM creates a default constructor which sets default values to the member variables (data members) i.e.,numeric data types are set to 0char data types are set to null character(‘’) and reference variables are set to null.
Example Program For Constructor  : http://pastie.org/6017560
Constructor Overloading
A technique in Java to use the method with the same name for different purposes is called overloading. Constructor overloading means the methods with same name as the class name but varying only with the parameters. Differentiation is made by the compiler based on the number of parameters passed and the type of parameters. 
Constructor Overloading Example : http://pastie.org/6018495
In the above example program, execution starts from main() and two objects d and d1 are created. Immediately, first parameter less constructor is called and the output is printed. Secondly, the parameterized constructor is executed and the output is shown. Now thed.display() and d1.display() are executed and the values as per the objects are printed.

0 comments:

Post a Comment